from datetime import datetime

from pydantic import BaseModel, ConfigDict, Field, field_validator

RoleName = str


class PermissionResponse(BaseModel):
    id: int
    name: str
    display_name: str
    description: str
    module: str
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class RoleBase(BaseModel):
    name: str = Field(min_length=3, max_length=80)
    display_name: str = Field(min_length=2, max_length=120)
    description: str = Field(default="", max_length=500)

    @field_validator("name")
    @classmethod
    def validate_name(cls, value: str) -> str:
        normalized = value.strip().lower()
        allowed = normalized.replace("_", "").replace("-", "").replace(".", "")
        if not allowed.isalnum():
            raise ValueError(
                "Rollenname darf nur Buchstaben, Zahlen, Punkt, Unterstrich und Bindestrich enthalten"
            )
        return normalized

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


class RoleCreate(RoleBase):
    permission_ids: list[int] = Field(default_factory=list)


class RoleUpdate(RoleBase):
    permission_ids: list[int] = Field(default_factory=list)


class RolePermissionUpdate(BaseModel):
    permission_ids: list[int] = Field(default_factory=list)


class RoleResponse(BaseModel):
    id: int
    name: str
    display_name: str
    description: str
    is_system: bool
    permissions: list[PermissionResponse]
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class CurrentUserResponse(BaseModel):
    id: int
    first_name: str
    last_name: str
    username: str
    email: str
    role: str
    permissions: list[str]
