from app.extensions import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

class User(UserMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('companies.id'), nullable=True)
    email = db.Column(db.String(200), unique=True, nullable=False)
    password_hash = db.Column(db.String(300), nullable=False)
    vorname = db.Column(db.String(100))
    nachname = db.Column(db.String(100))
    rolle = db.Column(db.String(20), default='mitarbeiter')
    aktiv = db.Column(db.Boolean, default=True)
    font_size = db.Column(db.String(10), default='1')
    profile_image = db.Column(db.String(255), nullable=True)
    letzter_login = db.Column(db.DateTime)
    erstellt_am = db.Column(db.DateTime, default=datetime.utcnow)

    darf_projekte_anlegen = db.Column(db.Boolean, default=False)
    darf_lv_verwalten = db.Column(db.Boolean, default=False)
    darf_preise_sehen = db.Column(db.Boolean, default=False)
    darf_aufmass_verwalten = db.Column(db.Boolean, default=False)
    darf_evergabe_nutzen = db.Column(db.Boolean, default=False)
    darf_kopfdaten_holen = db.Column(db.Boolean, default=False)
    darf_aufmass_uebertragen = db.Column(db.Boolean, default=False)
    hidden_modules = db.Column(db.Text, default='[]')

    def get_hidden_modules(self):
        import json
        try:
            return json.loads(self.hidden_modules or '[]')
        except (json.JSONDecodeError, TypeError):
            return []

    def set_hidden_modules(self, val):
        import json
        self.hidden_modules = json.dumps(val, ensure_ascii=False)

    @property
    def full_name(self):
        return f"{self.vorname or ''} {self.nachname or ''}".strip() or self.email

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_superadmin(self):
        return self.rolle == 'superadmin'

    def is_firmadmin(self):
        return self.rolle == 'firmadmin'

    def is_admin(self):
        return self.rolle in ('firmadmin', 'superadmin')

    def hat_zugriff(self, project, required='lesen'):
        if self.is_superadmin():
            return True
        if self.is_firmadmin():
            from app.models.project import Project
            return Project.query.get(project.id).company_id == self.company_id
        from app.models.project_access import ProjectAccess
        access = ProjectAccess.query.filter_by(
            user_id=self.id, project_id=project.id
        ).first()
        if not access:
            return False
        if required == 'lesen':
            return True
        if required == 'schreiben':
            return access.zugriff in ('lesen', 'schreiben')
        return False

    def __repr__(self):
        return f'<User {self.email} ({self.rolle})>'
