from typing import Optional, List, Annotated
from pydantic import BaseModel, Field, ConfigDict, field_validator, BeforeValidator
from datetime import datetime

StrId = Annotated[str, BeforeValidator(str)]


class DepartmentBase(BaseModel):
    name: str = Field(..., max_length=100)
    description: Optional[str] = None


class DepartmentCreate(DepartmentBase):
    @field_validator("name")
    @classmethod
    def validate_name(cls, v):
        if v is None:
            return v
        v = v.strip()
        if not v:
            raise ValueError("Department name cannot be empty")
        return v


class DepartmentUpdate(BaseModel):
    name: Optional[str] = Field(None, max_length=100)
    description: Optional[str] = None

    @field_validator("name")
    @classmethod
    def validate_name(cls, v):
        if v is None:
            return v
        v = v.strip()
        if not v:
            raise ValueError("Department name cannot be empty")
        return v


class DepartmentResponse(DepartmentBase):
    id: StrId
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class PaginatedDepartmentResponse(BaseModel):
    items: List[DepartmentResponse]
    total: int
    limit: int
    offset: int

    model_config = ConfigDict(from_attributes=True)