from __future__ import annotations

from fastapi import APIRouter, Depends, Query, status

from src.core.deps import get_categorias_service, require_api_key

from .schemas import CategoriaCreate, CategoriaOut, CategoriaUpdate, PaginatedCategorias
from .service import CategoriasService

router = APIRouter(prefix="/api/v1/categorias", tags=["Categorias"])


@router.get(
    "",
    summary="Listar categorias",
    response_model=PaginatedCategorias,
    response_model_exclude_none=True,
)
async def list_categorias(
    page: int = Query(1, ge=1, description="Página (>=1)"),
    limit: int | None = Query(None, ge=1, le=100, description="Tamanho da página (1-100)"),
    q: str | None = Query(None, description="Busca por nome/slug"),
    sort: str | None = Query(None, pattern="^(nome|slug|\\$createdAt)$", description="Campo de ordenação"),
    order: str | None = Query(None, pattern="^(asc|desc)$", description="Ordem da ordenação"),
    _: None = Depends(require_api_key),
    service: CategoriasService = Depends(get_categorias_service),
) -> PaginatedCategorias:
    return await service.list(page=page, limit=limit, q=q, sort=sort, order=order)


@router.get(
    "/{categoria_id}",
    summary="Obter categoria",
    response_model=CategoriaOut,
    response_model_exclude_none=True,
)
async def get_categoria(
    categoria_id: str,
    _: None = Depends(require_api_key),
    service: CategoriasService = Depends(get_categorias_service),
) -> CategoriaOut:
    return await service.get(categoria_id)


@router.post(
    "",
    status_code=status.HTTP_201_CREATED,
    summary="Criar categoria",
    response_model=CategoriaOut,
    response_model_exclude_none=True,
)
async def create_categoria(
    body: CategoriaCreate,
    _: None = Depends(require_api_key),
    service: CategoriasService = Depends(get_categorias_service),
) -> CategoriaOut:
    return await service.create(body)


@router.patch(
    "/{categoria_id}",
    summary="Atualizar categoria",
    response_model=CategoriaOut,
    response_model_exclude_none=True,
)
async def update_categoria(
    categoria_id: str,
    body: CategoriaUpdate,
    _: None = Depends(require_api_key),
    service: CategoriasService = Depends(get_categorias_service),
) -> CategoriaOut:
    return await service.update(categoria_id, body)


@router.delete("/{categoria_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Remover categoria")
async def delete_categoria(
    categoria_id: str,
    _: None = Depends(require_api_key),
    service: CategoriasService = Depends(get_categorias_service),
) -> None:
    await service.delete(categoria_id)
