from datetime import datetime, timezone
from sqlalchemy import event
from .. import db

class Quotation(db.Model):
    __tablename__ = 'mold_quotations'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('enterprise_users.id'), nullable=False)
    
    # Factory Information
    mold_shop_name = db.Column(db.String(100), nullable=False)
    mold_shop_country = db.Column(db.String(50), nullable=False)
    t1_shoe_factory_name = db.Column(db.String(100), nullable=False)
    t1_shoe_factory_country = db.Column(db.String(50), nullable=False)
    t2_component_factory_name = db.Column(db.String(100), nullable=False)
    t2_component_factory_country = db.Column(db.String(50), nullable=False)
    
    # Mold Information
    model_name = db.Column(db.String(100), nullable=False)
    tooling_id = db.Column(db.String(5), nullable=False)
    season = db.Column(db.String(10), nullable=False)
    stage = db.Column(db.String(10), nullable=False)
    type = db.Column(db.String(20), nullable=False)
    
    # Dates and Approvals
    issue_date = db.Column(db.Date, nullable=False)
    approved_by_mold_shop = db.Column(db.String(100), nullable=False)
    approved_by_t1_tooling = db.Column(db.String(100), nullable=False)
    approved_by_lo_tooling = db.Column(db.String(100), nullable=False)
    
    # Mold Specifications
    mold_main_type = db.Column(db.String(50), nullable=False)
    mold_sub_type = db.Column(db.String(50), nullable=False)
    mold_specific_type = db.Column(db.String(50), nullable=False)
    complexity_high_sidewall = db.Column(db.Boolean, default=False)
    sliders_count = db.Column(db.Integer, nullable=False)
    cavity_count = db.Column(db.Float, nullable=False)
    digital_texture_type = db.Column(db.String(50), nullable=False)
    
    # Calculation Results
    base_price = db.Column(db.Float, nullable=False)
    tax_rate = db.Column(db.Float)
    total_cost = db.Column(db.Float, nullable=False)
    
    # Metadata
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    is_archived = db.Column(db.Boolean, default=False)
    
    __table_args__ = (
        db.Index('ix_quotation_user_id', user_id),
        db.Index('ix_quotation_created_at', created_at),
        db.Index('ix_quotation_issue_date', issue_date),
    )
    
    def __repr__(self):
        return f'<Quotation {self.id}>'

# Event listeners for model changes
@event.listens_for(Quotation, 'before_insert')
def set_quotation_timestamps(mapper, connection, target):
    target.created_at = datetime.now(timezone.utc) 