"""
用户相关数据模型
"""
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, Boolean, DateTime, Integer, ForeignKey, Text, Index
from sqlalchemy.orm import relationship
from app.db.base import Base


class User(Base):
    """用户表 - 匹配数据库实际结构"""

    __tablename__ = "users"

    id = Column(BigInteger, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(100), unique=True, nullable=False)
    hashed_password = Column(String(255), nullable=False)
    full_name = Column(String(100), nullable=True)
    phone = Column(String(20), nullable=True)
    avatar_url = Column(String(500), nullable=True)
    department = Column(String(100), nullable=True)
    position = Column(String(100), nullable=True)
    employee_id = Column(String(50), nullable=True, index=True)
    is_active = Column(Boolean, default=True, nullable=False)
    is_superuser = Column(Boolean, default=False, nullable=False)
    last_login_at = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    # 兼容性属性 - 让旧代码也能工作
    @property
    def password_hash(self):
        return self.hashed_password

    @property
    def real_name(self):
        return self.full_name or self.username

    @property
    def status(self):
        return "active" if self.is_active else "disabled"

    @property
    def is_admin(self):
        return self.is_superuser

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username}, full_name={self.full_name})>"


class Role(Base):
    """角色表"""

    __tablename__ = "roles"

    id = Column(BigInteger, primary_key=True, index=True)
    role_name = Column(String(50), unique=True, nullable=False)
    role_code = Column(String(50), unique=True, nullable=False)
    description = Column(Text, nullable=True)
    status = Column(String(20), default="active", nullable=False, comment="active, disabled")
    sort_order = Column(Integer, default=0, nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    updated_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    deleted_at = Column(DateTime, nullable=True)
    deleted_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    created_user = relationship("User", foreign_keys=[created_by])
    updated_user = relationship("User", foreign_keys=[updated_by])
    deleted_user = relationship("User", foreign_keys=[deleted_by])

    # 多对多关系：角色 -> 权限（通过 RolePermission 关联表）
    permissions = relationship("Permission", secondary="role_permissions", primaryjoin="Role.id == RolePermission.role_id", secondaryjoin="Permission.id == RolePermission.permission_id", viewonly=True)

    def __repr__(self):
        return f"<Role(id={self.id}, role_code={self.role_code}, role_name={self.role_name})>"


class UserRole(Base):
    """用户角色关联表"""

    __tablename__ = "user_roles"

    id = Column(BigInteger, primary_key=True, index=True)
    user_id = Column(BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    role_id = Column(BigInteger, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    user = relationship("User", foreign_keys=[user_id])
    role = relationship("Role", foreign_keys=[role_id])
    created_user = relationship("User", foreign_keys=[created_by])

    # 索引
    __table_args__ = (
        Index("idx_user_roles_user", "user_id"),
        Index("idx_user_roles_role", "role_id"),
    )


class Permission(Base):
    """权限表"""

    __tablename__ = "permissions"

    id = Column(BigInteger, primary_key=True, index=True)
    permission_name = Column(String(100), unique=True, nullable=False)
    permission_code = Column(String(100), unique=True, nullable=False)
    module = Column(String(50), nullable=False, comment="模块: asset, device_type, org, user, system")
    resource = Column(String(50), nullable=True, comment="资源: asset, device_type, organization")
    action = Column(String(50), nullable=True, comment="操作: create, read, update, delete, export, import")
    description = Column(Text, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)

    def __repr__(self):
        return f"<Permission(id={self.id}, permission_code={self.permission_code}, permission_name={self.permission_name})>"


class RolePermission(Base):
    """角色权限关联表"""

    __tablename__ = "role_permissions"

    id = Column(BigInteger, primary_key=True, index=True)
    role_id = Column(BigInteger, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
    permission_id = Column(BigInteger, ForeignKey("permissions.id", ondelete="CASCADE"), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    role = relationship("Role", foreign_keys=[role_id])
    permission = relationship("Permission", foreign_keys=[permission_id])
    created_user = relationship("User", foreign_keys=[created_by])

    # 索引
    __table_args__ = (
        Index("idx_role_permissions_role", "role_id"),
        Index("idx_role_permissions_permission", "permission_id"),
    )
