import uuid
from datetime import datetime

from pydantic import BaseModel, EmailStr, field_validator


class RegisterRequest(BaseModel):
    email: EmailStr
    password: str
    plan: str = "free"

    @field_validator("plan")
    @classmethod
    def validate_plan(cls, v: str) -> str:
        if v not in ("free", "starter", "pro"):
            raise ValueError("Invalid plan. Choose: free, starter, pro")
        return v


class LoginRequest(BaseModel):
    email: EmailStr
    password: str


class TokenResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"


class UserResponse(BaseModel):
    id: uuid.UUID
    email: str
    api_key: str
    plan: str
    created_at: datetime

    model_config = {"from_attributes": True}


class CollectionCreate(BaseModel):
    name: str


class CollectionResponse(BaseModel):
    id: uuid.UUID
    user_id: uuid.UUID
    name: str
    ticket_count: int
    created_at: datetime

    model_config = {"from_attributes": True}


class TicketMessage(BaseModel):
    role: str
    text: str


class TicketInput(BaseModel):
    ticket_id: int | str
    category: str = ""
    description: str = ""
    client: str = ""
    messages: list[TicketMessage] = []

    @field_validator("ticket_id", mode="before")
    @classmethod
    def coerce_ticket_id(cls, v: int | str) -> str:
        return str(v)


class TicketsUpload(BaseModel):
    tickets: list[TicketInput]


class TicketsUploadResponse(BaseModel):
    processed: int
    skipped: int
    collection_ticket_count: int
