from __future__ import annotations

from fastapi import APIRouter, Depends, Query, status

from src.core.deps import get_faturas_service, require_api_key

from .schemas import FaturaCreate, FaturaOut, FaturaUpdate, PaginatedFaturas
from .service import FaturasService

router = APIRouter(prefix="/api/v1/faturas", tags=["Faturas"])


@router.get("", summary="Listar faturas", response_model=PaginatedFaturas, response_model_exclude_none=True)
async def list_faturas(
    page: int = Query(1, ge=1),
    limit: int | None = Query(None, ge=1, le=100),
    q: str | None = Query(None, description="Busca por status"),
    sort: str | None = Query(None, pattern="^(data-vencimento|\\$createdAt)$"),
    order: str | None = Query(None, pattern="^(asc|desc)$"),
    status_filter: str | None = Query(None, pattern="^(pendente|pago|cancelado)$", description="Filtrar por status"),
    _: None = Depends(require_api_key),
    service: FaturasService = Depends(get_faturas_service),
) -> PaginatedFaturas:
    return await service.list(page=page, limit=limit, q=q, sort=sort, order=order, status=status_filter)


@router.get("/{fatura_id}", summary="Obter fatura", response_model=FaturaOut, response_model_exclude_none=True)
async def get_fatura(
    fatura_id: str,
    _: None = Depends(require_api_key),
    service: FaturasService = Depends(get_faturas_service),
) -> FaturaOut:
    return await service.get(fatura_id)


@router.post("", status_code=status.HTTP_201_CREATED, summary="Criar fatura", response_model=FaturaOut, response_model_exclude_none=True)
async def create_fatura(
    body: FaturaCreate,
    _: None = Depends(require_api_key),
    service: FaturasService = Depends(get_faturas_service),
) -> FaturaOut:
    return await service.create(body)


@router.patch("/{fatura_id}", summary="Atualizar fatura", response_model=FaturaOut, response_model_exclude_none=True)
async def update_fatura(
    fatura_id: str,
    body: FaturaUpdate,
    _: None = Depends(require_api_key),
    service: FaturasService = Depends(get_faturas_service),
) -> FaturaOut:
    return await service.update(fatura_id, body)


@router.delete("/{fatura_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Remover fatura")
async def delete_fatura(
    fatura_id: str,
    _: None = Depends(require_api_key),
    service: FaturasService = Depends(get_faturas_service),
) -> None:
    await service.delete(fatura_id)
