# -*- coding: utf-8 -*-
"""
用户相关 Pydantic v2 校验模型 (DTO)
用于请求体验证和响应序列化，与 ORM 模型解耦。
"""

from datetime import datetime

from pydantic import BaseModel, Field, ConfigDict


# ---- 请求模型 ----

class UserLogin(BaseModel):
    """登录请求"""
    username: str = Field(..., min_length=2, max_length=50, examples=["admin"])
    password: str = Field(..., min_length=6, max_length=128)


class UserCreate(BaseModel):
    """创建用户请求 (管理员操作)"""
    username: str = Field(..., min_length=2, max_length=50)
    password: str = Field(..., min_length=6, max_length=128)
    role: str = Field(default="user", pattern=r"^(admin|user)$")
    permissions: str = Field(default="view,edit")


class UserUpdate(BaseModel):
    """更新用户请求 (部分更新)"""
    password: str | None = Field(default=None, min_length=6, max_length=128)
    role: str | None = Field(default=None, pattern=r"^(admin|user)$")
    permissions: str | None = None
    is_active: bool | None = None


# ---- 响应模型 ----

class UserOut(BaseModel):
    """用户信息响应 (脱敏，不含密码哈希)"""
    model_config = ConfigDict(from_attributes=True)  # 支持从 ORM 对象自动转换

    id: int
    username: str
    role: str
    permissions: str
    is_active: bool
    created_at: datetime


class Token(BaseModel):
    """JWT 令牌响应"""
    access_token: str
    token_type: str = "bearer"
    role: str
    username: str
