from __future__ import annotations

from fastapi import APIRouter, Depends, Query, status

from typing import TYPE_CHECKING

from src.core.deps import get_carrinhos_service, require_api_key
from src.modules.carrinhos.schemas import (
    CarrinhoCreateRequest,
    CarrinhoOut,
    CarrinhoUpdateRequest,
)

from src.modules.carrinhos.service import CarrinhosService

if TYPE_CHECKING:
    pass

router = APIRouter(prefix="/api/v1/carrinhos", tags=["Carrinhos"])


@router.get(
    "",
    summary="Listar carrinhos",
    description=(
        "Retorna uma lista paginada de carrinhos com suporte a busca textual e ordenação. "
        "Inclua o header opcional `x-api-key` quando configurado."
    ),
    response_model=dict,
    responses={
        status.HTTP_200_OK: {
            "description": "Resposta bem-sucedida",
            "content": {
                "application/json": {
                    "example": {
                        "page": 1,
                        "limit": 20,
                        "total": 1,
                        "items": [
                            {
                                "id": "cart_1",
                                "itens": ["item_1", "item_2"],
                                "codigoInterno": "CART-001",
                                "labNome": ["Lab A"],
                                "quantidade": [2, 1],
                                "valorTotal": [19.9, 9.5],
                                "usuarios": "user_1",
                                "createdAt": "2025-09-29T12:00:00.000Z",
                                "updatedAt": "2025-09-29T12:00:00.000Z",
                            }
                        ],
                    }
                }
            },
        },
        status.HTTP_400_BAD_REQUEST: {
            "description": "Parâmetros inválidos",
            "content": {"application/json": {"example": {"detail": "Invalid sort field."}}},
        },
    },
)
async def list_carrinhos(
    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: CarrinhosService = Depends(get_carrinhos_service),
) -> dict:
    normalized_order = order.lower() if order else None
    return await service.list(page=page, limit=limit, q=q, sort=sort, order=normalized_order)


@router.get(
    "/{carrinho_id}",
    summary="Detalhar carrinho",
    description="Busca um carrinho pelo identificador, retornando itens e metadados. Header `x-api-key` opcional.",
    response_model=CarrinhoOut,
    responses={
        status.HTTP_200_OK: {
            "description": "Carrinho localizado",
            "content": {
                "application/json": {
                    "example": {
                        "id": "cart_1",
                        "itens": ["item_1"],
                        "codigoInterno": "CART-001",
                        "labNome": ["Lab A"],
                        "quantidade": [1],
                        "valorTotal": [19.9],
                        "usuarios": "user_1",
                        "createdAt": "2025-09-29T12:00:00.000Z",
                        "updatedAt": "2025-09-29T12:00:00.000Z",
                    }
                }
            },
        },
        status.HTTP_404_NOT_FOUND: {
            "description": "Carrinho não encontrado",
            "content": {"application/json": {"example": {"detail": "Carrinho não encontrado."}}},
        },
    },
)
async def get_carrinho(
    carrinho_id: str,
    _: None = Depends(require_api_key),
    service: CarrinhosService = Depends(get_carrinhos_service),
) -> CarrinhoOut:
    return await service.get(carrinho_id)


@router.post(
    "",
    summary="Criar carrinho",
    description="Cria um novo carrinho com itens, totais e vínculo de usuário. Header `x-api-key` opcional.",
    response_model=CarrinhoOut,
    status_code=status.HTTP_201_CREATED,
    responses={
        status.HTTP_201_CREATED: {
            "description": "Carrinho criado",
            "content": {
                "application/json": {
                    "example": {
                        "id": "cart_2",
                        "itens": ["item_3"],
                        "codigoInterno": "CART-002",
                        "labNome": ["Lab B"],
                        "quantidade": [3],
                        "valorTotal": [29.7],
                        "usuarios": "user_2",
                        "createdAt": "2025-09-29T12:20:00.000Z",
                        "updatedAt": "2025-09-29T12:20:00.000Z",
                    }
                }
            },
        },
        status.HTTP_400_BAD_REQUEST: {
            "description": "Dados inválidos",
            "content": {"application/json": {"example": {"detail": "codigoInterno não pode ser vazio."}}},
        },
    },
)
async def create_carrinho(
    payload: CarrinhoCreateRequest,
    _: None = Depends(require_api_key),
    service: CarrinhosService = Depends(get_carrinhos_service),
) -> CarrinhoOut:
    return await service.create(payload)


@router.patch(
    "/{carrinho_id}",
    summary="Atualizar carrinho",
    description="Atualiza parcialmente um carrinho existente. Header `x-api-key` opcional.",
    response_model=CarrinhoOut,
    responses={
        status.HTTP_200_OK: {
            "description": "Carrinho atualizado",
            "content": {
                "application/json": {
                    "example": {
                        "id": "cart_1",
                        "itens": ["item_1", "item_2"],
                        "codigoInterno": "CART-001",
                        "labNome": ["Lab A"],
                        "quantidade": [2, 1],
                        "valorTotal": [19.9, 9.5],
                        "usuarios": "user_1",
                        "createdAt": "2025-09-29T12:00:00.000Z",
                        "updatedAt": "2025-09-29T12:05:00.000Z",
                    }
                }
            },
        },
        status.HTTP_404_NOT_FOUND: {
            "description": "Carrinho não encontrado",
            "content": {"application/json": {"example": {"detail": "Carrinho não encontrado."}}},
        },
    },
)
async def update_carrinho(
    carrinho_id: str,
    payload: CarrinhoUpdateRequest,
    _: None = Depends(require_api_key),
    service: CarrinhosService = Depends(get_carrinhos_service),
) -> CarrinhoOut:
    return await service.update(carrinho_id, payload)


@router.delete(
    "/{carrinho_id}",
    summary="Remover carrinho",
    description="Remove um carrinho e seus vínculos. Header `x-api-key` opcional.",
    status_code=status.HTTP_204_NO_CONTENT,
    responses={
        status.HTTP_204_NO_CONTENT: {"description": "Carrinho removido"},
        status.HTTP_404_NOT_FOUND: {
            "description": "Carrinho não encontrado",
            "content": {"application/json": {"example": {"detail": "Carrinho não encontrado."}}},
        },
    },
)
async def delete_carrinho(
    carrinho_id: str,
    _: None = Depends(require_api_key),
    service: CarrinhosService = Depends(get_carrinhos_service),
) -> None:
    await service.delete(carrinho_id)
