"""Supplement search and detail endpoints."""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.supplement import Supplement
from app.schemas.supplement import SupplementResponse, SupplementSearchResponse

router = APIRouter()


@router.get("/search", response_model=SupplementSearchResponse)
async def search_supplements(
    q: str = Query(..., min_length=1, max_length=200, description="Search query"),
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
):
    """Search supplements by name. Returns paginated results."""
    offset = (page - 1) * size
    base_query = select(Supplement).where(Supplement.product_name.ilike(f"%{q}%"))

    total_result = await db.execute(select(func.count()).select_from(base_query.subquery()))
    total = total_result.scalar_one()

    result = await db.execute(
        base_query.offset(offset).limit(size).order_by(Supplement.product_name)
    )
    items = result.scalars().all()

    return SupplementSearchResponse(items=items, total=total, page=page, size=size)


@router.get("/{supplement_id}", response_model=SupplementResponse)
async def get_supplement(supplement_id: int, db: AsyncSession = Depends(get_db)):
    """Get supplement detail by ID."""
    result = await db.execute(select(Supplement).where(Supplement.id == supplement_id))
    supplement = result.scalar_one_or_none()
    if not supplement:
        raise HTTPException(status_code=404, detail="Supplement not found")
    return supplement
