from app.extensions import db
from datetime import datetime

class CustomModule(db.Model):
    __tablename__ = 'custom_modules'

    id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'), nullable=True)
    original_template_id = db.Column(db.Integer, db.ForeignKey('custom_modules.id'), nullable=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text, default='')
    kategorie = db.Column(db.String(50), default='allgemein')
    icon = db.Column(db.String(50), default='🔧')
    form_json = db.Column(db.Text, default='[]')
    rules_json = db.Column(db.Text, default='[]')
    is_template = db.Column(db.Boolean, default=False)
    sort_index = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True)
    created_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    company = db.relationship('Company', backref='custom_modules', foreign_keys=[company_id])
    template = db.relationship('CustomModule', backref='copies', remote_side=[id])
    creator = db.relationship('User', backref='created_custom_modules', foreign_keys=[created_by])

    def to_dict(self):
        return {
            'id': self.id,
            'company_id': self.company_id,
            'original_template_id': self.original_template_id,
            'name': self.name,
            'description': self.description,
            'kategorie': self.kategorie,
            'icon': self.icon,
            'is_template': self.is_template,
            'sort_index': self.sort_index,
            'is_active': self.is_active,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
        }

    def __repr__(self):
        return f'<CustomModule {self.name} ({"template" if self.is_template else "company"})>'


class CustomModuleAssignment(db.Model):
    __tablename__ = 'custom_module_assignments'

    id = db.Column(db.Integer, primary_key=True)
    module_id = db.Column(db.Integer, db.ForeignKey('custom_modules.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    can_edit = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    module = db.relationship('CustomModule', backref='assignments')
    user = db.relationship('User', backref='custom_module_assignments')

    __table_args__ = (
        db.UniqueConstraint('module_id', 'user_id', name='uq_module_user'),
    )
