"""
Schema Pydantic per utenti.
"""

import uuid
from datetime import datetime
from typing import Literal

from pydantic import BaseModel, EmailStr, Field, field_validator

UserRoleType = Literal["super_admin", "admin", "supervisor", "operator", "readonly"]


# ─── Request ──────────────────────────────────────────────────────────────────

class UserCreateRequest(BaseModel):
    email: EmailStr
    password: str = Field(min_length=8)
    full_name: str = Field(min_length=2, max_length=255)
    role: UserRoleType = "operator"

    @field_validator("password")
    @classmethod
    def validate_password(cls, v: str) -> str:
        if len(v) < 8:
            raise ValueError("La password deve essere almeno 8 caratteri")
        if not any(c.isupper() for c in v):
            raise ValueError("Almeno una lettera maiuscola richiesta")
        if not any(c.isdigit() for c in v):
            raise ValueError("Almeno un numero richiesto")
        return v

    @field_validator("role")
    @classmethod
    def validate_role_not_superadmin(cls, v: str) -> str:
        if v == "super_admin":
            raise ValueError("Non è possibile creare utenti super_admin via API")
        return v


class UserUpdateRequest(BaseModel):
    full_name: str | None = Field(default=None, min_length=2, max_length=255)
    role: UserRoleType | None = None
    is_active: bool | None = None

    @field_validator("role")
    @classmethod
    def validate_role_not_superadmin(cls, v: str | None) -> str | None:
        if v == "super_admin":
            raise ValueError("Non è possibile assegnare il ruolo super_admin via API")
        return v


class UserPasswordResetRequest(BaseModel):
    new_password: str = Field(min_length=8)

    @field_validator("new_password")
    @classmethod
    def validate_password(cls, v: str) -> str:
        if not any(c.isupper() for c in v):
            raise ValueError("Almeno una lettera maiuscola richiesta")
        if not any(c.isdigit() for c in v):
            raise ValueError("Almeno un numero richiesto")
        return v


# ─── Response ─────────────────────────────────────────────────────────────────

class UserResponse(BaseModel):
    id: uuid.UUID
    tenant_id: uuid.UUID
    email: str
    full_name: str
    role: str
    is_active: bool
    totp_enabled: bool
    last_login_at: datetime | None
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class UserListResponse(BaseModel):
    items: list[UserResponse]
    total: int
    page: int
    page_size: int
    pages: int
