from __future__ import annotations

from fastapi import APIRouter, Depends, Query, status

from src.core.deps import get_subcategorias_service, require_api_key
from src.modules.subcategorias.schemas import SubcategoriaCreate, SubcategoriaOut, SubcategoriaUpdate
from src.modules.subcategorias.service import SubcategoriasService

router = APIRouter(prefix="/api/v1/subcategorias", tags=["Subcategorias"])

_ALLOWED_SORT_FIELDS = {"nome", "$createdAt"}


@router.get(
    "",
    summary="List subcategorias",
    description="Return a paginated list of subcategorias with optional filtering, sorting, and search.",
    response_model=dict,
    responses={
        status.HTTP_200_OK: {
            "description": "Successful response",
            "content": {
                "application/json": {
                    "example": {
                        "page": 1,
                        "limit": 20,
                        "total": 2,
                        "items": [
                            {
                                "id": "sub_1",
                                "nome": "Analgésicos",
                                "categoriaId": "cat_1",
                                "createdAt": "2025-09-29T12:00:00.000Z",
                                "updatedAt": "2025-09-29T12:00:00.000Z",
                            },
                            {
                                "id": "sub_2",
                                "nome": "Vitaminas",
                                "categoriaId": "cat_2",
                                "createdAt": "2025-09-29T12:10:00.000Z",
                                "updatedAt": "2025-09-29T12:10:00.000Z",
                            },
                        ],
                    }
                }
            },
        },
        status.HTTP_400_BAD_REQUEST: {
            "description": "Invalid request parameters",
            "content": {
                "application/json": {
                    "example": {"detail": "Invalid sort field."}
                }
            },
        },
    },
)
async def list_subcategorias(
    page: int = Query(1, ge=1),
    limit: int | None = Query(None, ge=1, le=100),
    q: str | None = Query(None, min_length=1),
    sort: str | None = Query(None),
    order: str | None = Query(None, pattern="^(?i)(asc|desc)$"),
    _: None = Depends(require_api_key),
    service: SubcategoriasService = Depends(get_subcategorias_service),
) -> dict:
    normalized_order = order.lower() if order else None
    normalized_sort = sort if sort in _ALLOWED_SORT_FIELDS else sort
    return await service.list(page=page, limit=limit, q=q, sort=normalized_sort, order=normalized_order)


@router.get(
    "/{subcategoria_id}",
    summary="Retrieve subcategoria",
    description="Fetch a single subcategoria by its identifier, including audit metadata.",
    response_model=SubcategoriaOut,
    responses={
        status.HTTP_200_OK: {
            "description": "Subcategoria details",
            "content": {
                "application/json": {
                    "example": {
                        "id": "sub_1",
                        "nome": "Analgésicos",
                        "categoriaId": "cat_1",
                        "createdAt": "2025-09-29T12:00:00.000Z",
                        "updatedAt": "2025-09-29T12:00:00.000Z",
                    }
                }
            },
        },
        status.HTTP_404_NOT_FOUND: {
            "description": "Subcategoria not found",
            "content": {"application/json": {"example": {"detail": "Subcategoria not found."}}},
        },
    },
)
async def get_subcategoria(
    subcategoria_id: str,
    _: None = Depends(require_api_key),
    service: SubcategoriasService = Depends(get_subcategorias_service),
) -> SubcategoriaOut:
    return await service.get(subcategoria_id)


@router.post(
    "",
    summary="Create subcategoria",
    description="Create a new subcategoria linked to an optional categoria.",
    response_model=SubcategoriaOut,
    status_code=status.HTTP_201_CREATED,
    responses={
        status.HTTP_201_CREATED: {
            "description": "Subcategoria created",
            "content": {
                "application/json": {
                    "example": {
                        "id": "sub_3",
                        "nome": "Suplementos",
                        "categoriaId": "cat_2",
                        "createdAt": "2025-09-29T12:20:00.000Z",
                        "updatedAt": "2025-09-29T12:20:00.000Z",
                    }
                }
            },
        },
        status.HTTP_409_CONFLICT: {
            "description": "Subcategoria already exists",
            "content": {
                "application/json": {
                    "example": {"detail": "Subcategoria already exists."}
                }
            },
        },
    },
)
async def create_subcategoria(
    payload: SubcategoriaCreate,
    _: None = Depends(require_api_key),
    service: SubcategoriasService = Depends(get_subcategorias_service),
) -> SubcategoriaOut:
    return await service.create(payload)


@router.patch(
    "/{subcategoria_id}",
    summary="Update subcategoria",
    description="Update an existing subcategoria partially, supporting relation updates.",
    response_model=SubcategoriaOut,
    responses={
        status.HTTP_200_OK: {
            "description": "Subcategoria updated",
            "content": {
                "application/json": {
                    "example": {
                        "id": "sub_1",
                        "nome": "Analgésicos",
                        "categoriaId": "cat_1",
                        "createdAt": "2025-09-29T12:00:00.000Z",
                        "updatedAt": "2025-09-29T12:05:00.000Z",
                    }
                }
            },
        },
        status.HTTP_404_NOT_FOUND: {
            "description": "Subcategoria not found",
            "content": {"application/json": {"example": {"detail": "Subcategoria not found."}}},
        },
        status.HTTP_409_CONFLICT: {
            "description": "Subcategoria already exists",
            "content": {
                "application/json": {
                    "example": {"detail": "Subcategoria already exists."}
                }
            },
        },
    },
)
async def update_subcategoria(
    subcategoria_id: str,
    payload: SubcategoriaUpdate,
    _: None = Depends(require_api_key),
    service: SubcategoriasService = Depends(get_subcategorias_service),
) -> SubcategoriaOut:
    return await service.update(subcategoria_id, payload)


@router.delete(
    "/{subcategoria_id}",
    summary="Delete subcategoria",
    description="Remove a subcategoria from the catalog.",
    status_code=status.HTTP_204_NO_CONTENT,
    responses={
        status.HTTP_204_NO_CONTENT: {"description": "Subcategoria removed"},
        status.HTTP_404_NOT_FOUND: {
            "description": "Subcategoria not found",
            "content": {"application/json": {"example": {"detail": "Subcategoria not found."}}},
        },
    },
)
async def delete_subcategoria(
    subcategoria_id: str,
    _: None = Depends(require_api_key),
    service: SubcategoriasService = Depends(get_subcategorias_service),
) -> None:
    await service.delete(subcategoria_id)
