import uuid
from datetime import datetime
from typing import Optional

from pydantic import BaseModel, ConfigDict, EmailStr, Field


# ── Department ──────────────────────────────────────────────────────────────

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


class DepartmentCreate(DepartmentBase):
    pass


class DepartmentResponse(DepartmentBase):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    user_count: Optional[int] = None


# ── User ────────────────────────────────────────────────────────────────────

class UserBase(BaseModel):
    email: EmailStr
    full_name: str = Field(..., max_length=200)
    employee_id: Optional[str] = Field(None, max_length=50)
    role: str = Field(default="employee", max_length=20)


class UserCreate(BaseModel):
    email: EmailStr
    full_name: str = Field(..., max_length=200)
    password: str = Field(..., min_length=6)
    department_id: Optional[uuid.UUID] = None


class UserUpdate(BaseModel):
    full_name: Optional[str] = Field(None, max_length=200)
    email: Optional[EmailStr] = None
    department_id: Optional[uuid.UUID] = None
    role: Optional[str] = Field(None, max_length=20)
    is_active: Optional[bool] = None
    github_username: Optional[str] = Field(None, max_length=100)
    udemy_email: Optional[EmailStr] = None


class UserResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    employee_id: Optional[str] = None
    email: EmailStr
    full_name: str
    department_id: Optional[uuid.UUID] = None
    department_name: Optional[str] = None
    role: str
    avatar_url: Optional[str] = None
    is_active: bool
    total_xp: int
    verified_xp: int
    current_level: str
    created_at: datetime


class UserProfile(UserResponse):
    """Extended user response with gamification details."""

    completions_count: int = 0
    badges_count: int = 0
    badges: list["BadgeResponse"] = []


# Deferred import to avoid circular dependency
from app.schemas.gamification import BadgeResponse  # noqa: E402

UserProfile.model_rebuild()
