"""User medication cabinet endpoints."""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.dependencies import require_device_id
from app.models.user_cabinet import UserCabinet
from app.schemas.cabinet import CabinetItemCreate, CabinetItemResponse, CabinetListResponse

router = APIRouter()


@router.get("", response_model=CabinetListResponse)
async def get_cabinet(
    device_id: str = Depends(require_device_id),
    db: AsyncSession = Depends(get_db),
):
    """Get all items in the user's medication cabinet."""
    result = await db.execute(
        select(UserCabinet)
        .where(UserCabinet.device_id == device_id)
        .order_by(UserCabinet.created_at.desc())
    )
    items = result.scalars().all()
    return CabinetListResponse(items=items, total=len(items))


@router.post("", response_model=CabinetItemResponse, status_code=201)
async def add_to_cabinet(
    payload: CabinetItemCreate,
    device_id: str = Depends(require_device_id),
    db: AsyncSession = Depends(get_db),
):
    """Add a drug or supplement to the user's cabinet."""
    # Check for duplicate
    existing = await db.execute(
        select(UserCabinet).where(
            UserCabinet.device_id == device_id,
            UserCabinet.item_type == payload.item_type,
            UserCabinet.item_id == payload.item_id,
        )
    )
    if existing.scalar_one_or_none():
        raise HTTPException(status_code=409, detail="Item already in cabinet")

    item = UserCabinet(
        device_id=device_id,
        item_type=payload.item_type,
        item_id=payload.item_id,
        nickname=payload.nickname,
    )
    db.add(item)
    await db.flush()
    await db.refresh(item)
    return item


@router.delete("/{cabinet_id}", status_code=204)
async def remove_from_cabinet(
    cabinet_id: int,
    device_id: str = Depends(require_device_id),
    db: AsyncSession = Depends(get_db),
):
    """Remove an item from the user's cabinet."""
    result = await db.execute(
        delete(UserCabinet).where(
            UserCabinet.id == cabinet_id,
            UserCabinet.device_id == device_id,
        )
    )
    if result.rowcount == 0:
        raise HTTPException(status_code=404, detail="Cabinet item not found")
