from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class CostFactor(db.Model):
    """Model for storing cost factors that can be managed via admin interface"""
    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String(50), nullable=False)  # 'mold', 'complexity', 'texture', 'tax'
    subcategory = db.Column(db.String(50))  # For mold types: 'Rubber', 'CMEVA', etc.
    name = db.Column(db.String(100), nullable=False)  # Factor name
    factor_value = db.Column(db.Float, nullable=False)  # The actual factor value
    calculation_formula = db.Column(db.String(200))  # For complexity factors
    percentage = db.Column(db.String(20))  # For display purposes
    description = db.Column(db.String(500))
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    updated_by = db.Column(db.Integer, db.ForeignKey('user.id'))
    
    # Relationship
    updater = db.relationship('User', backref='cost_factor_updates')
    
    def __repr__(self):
        return f'<CostFactor {self.category}:{self.name}={self.factor_value}>'

class CostFactorHistory(db.Model):
    """Model for tracking changes to cost factors"""
    id = db.Column(db.Integer, primary_key=True)
    cost_factor_id = db.Column(db.Integer, db.ForeignKey('cost_factor.id'), nullable=False)
    old_value = db.Column(db.Float)
    new_value = db.Column(db.Float, nullable=False)
    changed_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    changed_at = db.Column(db.DateTime, default=datetime.utcnow)
    change_reason = db.Column(db.String(500))
    
    # Relationships
    cost_factor = db.relationship('CostFactor', backref='history')
    user = db.relationship('User', backref='cost_factor_changes')
    
    def __repr__(self):
        return f'<CostFactorHistory {self.cost_factor_id}:{self.old_value}->{self.new_value}>' 