"""
用户模型
"""
from sqlalchemy import Column, String, DateTime, func
from sqlalchemy.dialects.mysql import CHAR
from sqlalchemy.orm import relationship
from app.core.database import Base
import uuid


class User(Base):
    """用户表"""
    __tablename__ = "users"

    id = Column(CHAR(36), primary_key=True, default=lambda: str(uuid.uuid4()), comment="用户ID")
    username = Column(String(50), unique=True, nullable=False, comment="用户名")
    email = Column(String(100), unique=True, nullable=False, comment="邮箱")
    password_hash = Column(String(255), nullable=False, comment="密码哈希")
    role = Column(String(20), default="user", comment="角色: admin/user（保留字段，用于向后兼容）")
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")

    # RBAC关系（多对多）
    roles = relationship("Role", secondary="user_roles", back_populates="users")

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username})>"
    
    def has_permission(self, permission_code: str) -> bool:
        """检查用户是否有指定权限"""
        # 如果是admin，拥有所有权限
        if self.role == "admin":
            return True
        
        # 检查用户的所有角色是否包含该权限
        for role in self.roles:
            for permission in role.permissions:
                if permission.code == permission_code:
                    return True
        return False
    
    def has_role(self, role_name: str) -> bool:
        """检查用户是否有指定角色"""
        # 如果是admin，拥有所有角色
        if self.role == "admin":
            return True
        
        return any(role.name == role_name for role in self.roles)