from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator

from app.schemas.rbac import RoleResponse

UserRole = str


class UserBase(BaseModel):
    first_name: str = Field(default="", max_length=100)
    last_name: str = Field(default="", max_length=100)
    username: str = Field(min_length=3, max_length=50)
    email: EmailStr
    role: UserRole = "support"
    role_id: int | None = None
    is_active: bool = True

    @field_validator("first_name", "last_name", "username", mode="before")
    @classmethod
    def normalize_text(cls, value: object) -> str:
        if value is None:
            return ""
        return str(value).strip()

    @field_validator("username")
    @classmethod
    def validate_username(cls, value: str) -> str:
        allowed = value.replace(".", "").replace("_", "").replace("-", "")
        if not allowed.isalnum():
            raise ValueError(
                "Benutzername darf nur Buchstaben, Zahlen, Punkt, Unterstrich und Bindestrich enthalten"
            )
        return value


class UserCreate(UserBase):
    password: str = Field(min_length=8, max_length=128)


class UserUpdate(UserBase):
    password: str | None = Field(default=None, max_length=128)

    @field_validator("password")
    @classmethod
    def validate_optional_password(cls, value: str | None) -> str | None:
        if value is None or value == "":
            return None
        if len(value) < 8:
            raise ValueError("Passwort muss mindestens 8 Zeichen lang sein")
        return value


class UserPasswordUpdate(BaseModel):
    password: str = Field(min_length=8, max_length=128)


class LoginRequest(BaseModel):
    username: str
    password: str


class UserResponse(BaseModel):
    id: int
    first_name: str
    last_name: str
    username: str
    email: EmailStr
    role: UserRole
    role_id: int
    primary_role: RoleResponse
    is_active: bool
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class LoginResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"
    expires_in: int
    user: UserResponse
