from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json

db = SQLAlchemy()

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False, index=True)
    password = db.Column(db.String(255), nullable=False)
    default_location = db.Column(db.String(10))
    active = db.Column(db.Boolean, default=True)
    super_admin = db.Column(db.Boolean, default=False)
    
    # Permissions stored as JSON
    permissions_json = db.Column(db.Text, default='{}')
    location_settings_json = db.Column(db.Text, default='{}')
    
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    @property
    def permissions(self):
        """Get permissions as dictionary"""
        return json.loads(self.permissions_json) if self.permissions_json else {}
    
    @permissions.setter
    def permissions(self, value):
        """Set permissions from dictionary"""
        self.permissions_json = json.dumps(value)
    
    @property
    def locationSettings(self):
        """Get location settings as dictionary"""
        return json.loads(self.location_settings_json) if self.location_settings_json else {}
    
    @locationSettings.setter
    def locationSettings(self, value):
        """Set location settings from dictionary"""
        self.location_settings_json = json.dumps(value)
    
    def to_dict(self):
        """Convert user to dictionary matching JSON format"""
        return {
            'username': self.username,
            'password': self.password,
            'defaultLocation': self.default_location,
            'permissions': self.permissions,
            'locationSettings': self.locationSettings,
            'active': self.active,
            'superAdmin': self.super_admin
        }
    
    def __repr__(self):
        return f'<User {self.username}>'


class Product(db.Model):
    __tablename__ = 'products'
    
    id = db.Column(db.Integer, primary_key=True)
    product_code = db.Column(db.String(50), unique=True, nullable=False, index=True)
    category = db.Column(db.String(50))
    description = db.Column(db.Text)
    discontinued = db.Column(db.Boolean, default=False)
    location = db.Column(db.String(50))
    base_type = db.Column(db.String(50))
    
    # Store complex fields as JSON
    sub_type_json = db.Column(db.Text, default='{}')
    materials_json = db.Column(db.Text, default='[]')
    colors_json = db.Column(db.Text, default='[]')
    compatible_accessories_json = db.Column(db.Text, default='[]')
    image_config_json = db.Column(db.Text, default='{}')
    
    is_accessory = db.Column(db.Boolean, default=False)
    
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    @property
    def subType(self):
        return json.loads(self.sub_type_json) if self.sub_type_json else {}
    
    @subType.setter
    def subType(self, value):
        self.sub_type_json = json.dumps(value)
    
    @property
    def materials(self):
        return json.loads(self.materials_json) if self.materials_json else []
    
    @materials.setter
    def materials(self, value):
        self.materials_json = json.dumps(value)
    
    @property
    def colors(self):
        return json.loads(self.colors_json) if self.colors_json else []
    
    @colors.setter
    def colors(self, value):
        self.colors_json = json.dumps(value)
    
    @property
    def compatibleAccessories(self):
        return json.loads(self.compatible_accessories_json) if self.compatible_accessories_json else []
    
    @compatibleAccessories.setter
    def compatibleAccessories(self, value):
        self.compatible_accessories_json = json.dumps(value)
    
    @property
    def imageConfig(self):
        return json.loads(self.image_config_json) if self.image_config_json else {}
    
    @imageConfig.setter
    def imageConfig(self, value):
        self.image_config_json = json.dumps(value)
    
    def to_dict(self):
        """Convert product to dictionary matching JSON format"""
        return {
            'id': self.product_code,
            'productCode': self.product_code,
            'category': self.category,
            'description': self.description,
            'discontinued': self.discontinued,
            'location': self.location,
            'baseType': self.base_type,
            'subType': self.subType,
            'materials': self.materials,
            'colors': self.colors,
            'isAccessory': self.is_accessory,
            'compatibleAccessories': self.compatibleAccessories,
            'imageConfig': self.imageConfig
        }
    
    def __repr__(self):
        return f'<Product {self.product_code}>'


class Location(db.Model):
    __tablename__ = 'locations'
    
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(10), unique=True, nullable=False, index=True)
    name = db.Column(db.String(100), nullable=False)
    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)
    
    def to_dict(self):
        """Convert location to dictionary matching JSON format"""
        return {
            'code': self.code,
            'name': self.name
        }
    
    def __repr__(self):
        return f'<Location {self.code}: {self.name}>'


class ProductAttribute(db.Model):
    __tablename__ = 'product_attributes'
    
    id = db.Column(db.Integer, primary_key=True)
    
    # Store all attribute data as JSON
    statuses_json = db.Column(db.Text, default='[]')
    product_types_json = db.Column(db.Text, default='[]')
    code_modifiers_json = db.Column(db.Text, default='[]')
    
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    @property
    def statuses(self):
        return json.loads(self.statuses_json) if self.statuses_json else []
    
    @statuses.setter
    def statuses(self, value):
        self.statuses_json = json.dumps(value)
    
    @property
    def productTypes(self):
        return json.loads(self.product_types_json) if self.product_types_json else []
    
    @productTypes.setter
    def productTypes(self, value):
        self.product_types_json = json.dumps(value)
    
    @property
    def codeModifiers(self):
        return json.loads(self.code_modifiers_json) if self.code_modifiers_json else []
    
    @codeModifiers.setter
    def codeModifiers(self, value):
        self.code_modifiers_json = json.dumps(value)
    
    def to_dict(self):
        """Convert attributes to dictionary matching JSON format"""
        locations = Location.query.filter_by(active=True).all()
        return {
            'locations': [loc.to_dict() for loc in locations],
            'statuses': self.statuses,
            'productTypes': self.productTypes,
            'codeModifiers': self.codeModifiers
        }
    
    def __repr__(self):
        return f'<ProductAttribute {self.id}>'


# Additional models for other JSON files if needed

class Question(db.Model):
    __tablename__ = 'questions'
    
    id = db.Column(db.Integer, primary_key=True)
    question_data_json = db.Column(db.Text, nullable=False)
    order = db.Column(db.Integer, default=0)
    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)
    
    @property
    def questionData(self):
        return json.loads(self.question_data_json) if self.question_data_json else {}
    
    @questionData.setter
    def questionData(self, value):
        self.question_data_json = json.dumps(value)
    
    def __repr__(self):
        return f'<Question {self.id}>'


class Accessory(db.Model):
    __tablename__ = 'accessories'
    
    id = db.Column(db.Integer, primary_key=True)
    accessory_data_json = db.Column(db.Text, nullable=False)
    category = db.Column(db.String(50))
    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)
    
    @property
    def accessoryData(self):
        return json.loads(self.accessory_data_json) if self.accessory_data_json else {}
    
    @accessoryData.setter
    def accessoryData(self, value):
        self.accessory_data_json = json.dumps(value)
    
    def __repr__(self):
        return f'<Accessory {self.id}>'
