# -*- coding: utf-8 -*-
"""
用户 ORM 模型
对应数据库 users 表，使用 SQLAlchemy 2.0 Mapped 注解风格。
"""

from datetime import datetime, timezone

from sqlalchemy import String, func
from sqlalchemy.orm import Mapped, mapped_column

from app.core.database import Base


class User(Base):
    """用户表 - 存储账号、密码哈希、角色权限"""

    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    username: Mapped[str] = mapped_column(
        String(50), unique=True, nullable=False, index=True, comment="登录用户名"
    )
    password_hash: Mapped[str] = mapped_column(
        String(255), nullable=False, comment="bcrypt 哈希密码"
    )
    role: Mapped[str] = mapped_column(
        String(20), nullable=False, default="user", comment="角色: admin / user"
    )
    permissions: Mapped[str] = mapped_column(
        String(200), nullable=False, default="view,edit", comment="逗号分隔权限列表"
    )
    is_active: Mapped[bool] = mapped_column(
        default=True, comment="账户是否启用"
    )
    created_at: Mapped[datetime] = mapped_column(
        server_default=func.now(), comment="创建时间"
    )
    updated_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        onupdate=lambda: datetime.now(timezone.utc),
        comment="最后更新时间",
    )

    def __repr__(self) -> str:
        return f"<User(id={self.id}, username='{self.username}', role='{self.role}')>"
