from __future__ import annotations

from datetime import datetime
from typing import Any

from pydantic import BaseModel, ConfigDict, EmailStr, Field


class LoginRequest(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    username: str = Field(min_length=1, max_length=255)
    password: str = Field(min_length=1, max_length=128)
    tenant_id: str | None = Field(
        default=None,
        alias="tenantId",
        min_length=1,
        max_length=64,
    )


class AuthUserRead(BaseModel):
    username: str
    name: str
    role: str
    department: str = ""
    departmentName: str = ""
    position: str = ""
    grade: str = ""
    employeeNo: str = ""
    managerName: str = ""
    location: str = ""
    costCenter: str = ""
    financeOwnerName: str = ""
    riskProfile: dict[str, Any] = Field(default_factory=dict)
    roleCodes: list[str] = Field(default_factory=list)
    email: EmailStr | str
    avatar: str
    isAdmin: bool = False
    tenantId: str


class LoginResponse(BaseModel):
    ok: bool = True
    detail: str = "登录成功。"
    user: AuthUserRead
    sessionId: str = ""
    accessToken: str
    tokenType: str = "Bearer"
    expiresAt: datetime


class LogoutResponse(BaseModel):
    ok: bool = True
    detail: str = "已退出登录。"


class SessionFinishRequest(BaseModel):
    reason: str = Field(default="manual", max_length=40)
    lastActivityAt: datetime | None = None
    activityEventCount: int = Field(default=0, ge=0)
    pagePath: str = Field(default="", max_length=512)


class LogoutRequest(SessionFinishRequest):
    sessionId: str = Field(default="", max_length=64)


class SessionFinishResponse(BaseModel):
    ok: bool = True
    detail: str = "会话已结算。"
    sessionId: str = ""
    durationMs: int = 0
