from app.extensions import db
from datetime import datetime
import hashlib, secrets

def _generate_uid(company_name):
    raw = f"{company_name}-{secrets.token_hex(6)}"
    return hashlib.sha256(raw.encode()).hexdigest()[:12]

class License(db.Model):
    __tablename__ = 'licenses'

    id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'), nullable=False)
    uid = db.Column(db.String(64), unique=True, nullable=False)
    max_mitarbeiter = db.Column(db.Integer, default=5)
    max_module_slots = db.Column(db.Integer, default=5)
    unlimited_users = db.Column(db.Boolean, default=False)
    unlimited_modules = db.Column(db.Boolean, default=False)
    aktiv = db.Column(db.Boolean, default=True)
    erstellt_am = db.Column(db.DateTime, default=datetime.utcnow)

    modules = db.relationship('LicenseModule', backref='license', lazy='dynamic', cascade='all, delete-orphan')

    @property
    def used_users(self):
        from app.models.user import User
        return User.query.filter_by(company_id=self.company_id).count()

    @property
    def used_module_slots(self):
        from app.models.user_module import UserModulePermission
        from app.models.user import User
        return db.session.query(UserModulePermission.id).join(User, UserModulePermission.user_id==User.id)\
            .filter(User.company_id==self.company_id, UserModulePermission.aktiv==True).count()

    def user_slots_display(self):
        if self.unlimited_users: return '\u221e'
        return f'{self.used_users} / {self.max_mitarbeiter}'

    def module_slots_display(self):
        if self.unlimited_modules: return '\u221e'
        return f'{self.used_module_slots} / {self.max_module_slots}'

    @staticmethod
    def generate_uid(company_name):
        return _generate_uid(company_name)

    def __repr__(self):
        return f'<License {self.uid}>'

class LicenseModule(db.Model):
    __tablename__ = 'license_modules'

    id = db.Column(db.Integer, primary_key=True)
    license_id = db.Column(db.Integer, db.ForeignKey('licenses.id'), nullable=False)
    module_id = db.Column(db.Integer, db.ForeignKey('modules.id'), nullable=False)
    aktiv = db.Column(db.Boolean, default=True)

    module = db.relationship('Module', backref='license_assignments')
