"""items 域路由：只依赖 ItemRepo 协议，不关心底层是 MySQL 还是 MongoDB。"""

from fastapi import APIRouter, Query, status

from src.exceptions import NotFoundError
from src.items.dependencies import ItemRepoDep
from src.items.schemas import ItemCreate, ItemList, ItemOut, ItemUpdate

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


@router.post("", response_model=ItemOut, status_code=status.HTTP_201_CREATED)
async def create_item(data: ItemCreate, repo: ItemRepoDep):
    return await repo.create(data)


@router.get("/{item_id}", response_model=ItemOut)
async def get_item(item_id: str, repo: ItemRepoDep):
    item = await repo.get(item_id)
    if not item:
        raise NotFoundError(f"item {item_id} not found")
    return item


@router.get("", response_model=ItemList)
async def list_items(
    repo: ItemRepoDep,
    skip: int = Query(default=0, ge=0),
    limit: int = Query(default=20, ge=1, le=100),
):
    total, items = await repo.list(skip=skip, limit=limit)
    return ItemList(total=total, items=items)


@router.patch("/{item_id}", response_model=ItemOut)
async def update_item(item_id: str, data: ItemUpdate, repo: ItemRepoDep):
    item = await repo.update(item_id, data)
    if not item:
        raise NotFoundError(f"item {item_id} not found")
    return item


@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: str, repo: ItemRepoDep):
    if not await repo.delete(item_id):
        raise NotFoundError(f"item {item_id} not found")
