from app.extensions import db
from datetime import datetime

class LVPosition(db.Model):
    __tablename__ = 'lv_positionen'

    id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'), nullable=False)
    contract_id = db.Column(db.Integer, db.ForeignKey('contracts.id'), nullable=True)
    lv_name = db.Column(db.String(200), nullable=False)
    pos_nr = db.Column(db.String(50), nullable=False)
    order_index = db.Column(db.Integer, default=0)
    kurztext = db.Column(db.String(300))
    langtext = db.Column(db.Text)
    einheit = db.Column(db.String(10), default='ST')
    einzelpreis = db.Column(db.Float, default=0.0)
    gruppe = db.Column(db.String(100))
    rsa = db.Column(db.String(20))
    abschnitt = db.Column(db.String(100))
    notiz = db.Column(db.Text)
    favorite = db.Column(db.Boolean, default=False)
    erstellt_am = db.Column(db.DateTime, default=datetime.utcnow)

    __table_args__ = (
        db.UniqueConstraint('company_id', 'lv_name', 'pos_nr', name='uq_lv_position'),
    )

    def to_dict(self):
        return {
            'id': self.id,
            'lv_name': self.lv_name,
            'pos_nr': self.pos_nr,
            'kurztext': self.kurztext,
            'langtext': self.langtext,
            'einheit': self.einheit,
            'einzelpreis': self.einzelpreis,
            'gruppe': self.gruppe,
            'rsa': self.rsa,
            'abschnitt': self.abschnitt,
            'favorite': self.favorite,
        }

    def __repr__(self):
        return f'<LV {self.lv_name} | {self.pos_nr}>'
