"""
Modèle User - GMAO Collège
Gestion des utilisateurs et authentification
Compatible avec la base de données existante
"""
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, timezone
from ...extensions import db


class User(UserMixin, db.Model):
    """Utilisateur de l'application GMAO."""
    __tablename__ = "users"
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=True)
    password_hash = db.Column(db.String(256), nullable=False)
    full_name = db.Column(db.String(150), nullable=False, default="")
    role = db.Column(db.String(32), default="demandeur", nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    last_login = db.Column(db.DateTime, nullable=True)
    role_links = db.relationship("UserRole", foreign_keys="UserRole.user_id", back_populates="user", cascade="all, delete-orphan")
    permission_links = db.relationship("UserPermission", foreign_keys="UserPermission.user_id", back_populates="user", cascade="all, delete-orphan")
    
    def set_password(self, password):
        """Hash et stocke le mot de passe."""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """Vérifie le mot de passe."""
        return check_password_hash(self.password_hash, password)
    
    def is_admin(self):
        """Vérifie l'administration via le RBAC réel, jamais ``User.role``."""
        try:
            for link in self.role_links:
                if link.role and link.role.is_active and link.role.slug == "admin":
                    return True
                if link.role and link.role.is_active:
                    if any(
                        permission.effect == "allow"
                        and permission.permission
                        and permission.permission.is_active
                        and permission.permission.code == "*"
                        for permission in link.role.permission_links
                    ):
                        return True
        except Exception:
            from flask import current_app
            current_app.logger.exception("Erreur RBAC lors de la vérification admin")
        return False

    @property
    def canonical_role(self):
        from ..authorization import canonical_role
        return canonical_role(self.role)

    @property
    def role_label(self):
        from ..authorization import ROLE_LABELS
        roles = [link.role for link in self.role_links if link.role and link.role.is_active]
        if roles:
            return ", ".join(role.name for role in sorted(roles, key=lambda item: item.name.lower()))
        return "Aucun rôle RBAC"

    def has_permission(self, permission):
        from ..authorization import has_permission
        return has_permission(permission, self)
    
    def __repr__(self):
        return f"<User {self.username}>"


class Staff(db.Model):
    """Personnel du collège."""
    __tablename__ = "staff"
    
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100), nullable=False)
    last_name = db.Column(db.String(100), nullable=False)
    function = db.Column(db.String(200), nullable=True)  # Fonction/Poste
    department = db.Column(db.String(200), nullable=True)
    email = db.Column(db.String(200), nullable=True)
    phone = db.Column(db.String(20), nullable=True)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    
    @property
    def full_name(self):
        """Retourne le nom complet."""
        return f"{self.first_name} {self.last_name}"
    
    def __repr__(self):
        return f"<Staff {self.full_name}>"
