from __future__ import annotations

from fastapi import APIRouter, Depends, Query, status

from src.core.deps import get_laboratorios_service, require_api_key

from .schemas import LaboratorioCreate, LaboratorioOut, LaboratorioUpdate, PaginatedLaboratorios
from .service import LaboratoriosService

router = APIRouter(prefix="/api/v1/laboratorios", tags=["Laboratorios"])


@router.get("", summary="Listar laboratórios", response_model=PaginatedLaboratorios, response_model_exclude_none=True)
async def list_labs(
    page: int = Query(1, ge=1),
    limit: int | None = Query(None, ge=1, le=100),
    q: str | None = Query(None, description="Busca por nome"),
    sort: str | None = Query(None, pattern="^(nome|\\$createdAt)$"),
    order: str | None = Query(None, pattern="^(asc|desc)$"),
    _: None = Depends(require_api_key),
    service: LaboratoriosService = Depends(get_laboratorios_service),
) -> PaginatedLaboratorios:
    return await service.list(page=page, limit=limit, q=q, sort=sort, order=order)


@router.get("/{lab_id}", summary="Obter laboratório", response_model=LaboratorioOut, response_model_exclude_none=True)
async def get_lab(
    lab_id: str,
    _: None = Depends(require_api_key),
    service: LaboratoriosService = Depends(get_laboratorios_service),
) -> LaboratorioOut:
    return await service.get(lab_id)


@router.post("", status_code=status.HTTP_201_CREATED, summary="Criar laboratório", response_model=LaboratorioOut, response_model_exclude_none=True)
async def create_lab(
    body: LaboratorioCreate,
    _: None = Depends(require_api_key),
    service: LaboratoriosService = Depends(get_laboratorios_service),
) -> LaboratorioOut:
    return await service.create(body)


@router.patch("/{lab_id}", summary="Atualizar laboratório", response_model=LaboratorioOut, response_model_exclude_none=True)
async def update_lab(
    lab_id: str,
    body: LaboratorioUpdate,
    _: None = Depends(require_api_key),
    service: LaboratoriosService = Depends(get_laboratorios_service),
) -> LaboratorioOut:
    return await service.update(lab_id, body)


@router.delete("/{lab_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Remover laboratório")
async def delete_lab(
    lab_id: str,
    _: None = Depends(require_api_key),
    service: LaboratoriosService = Depends(get_laboratorios_service),
) -> None:
    await service.delete(lab_id)
