"""Drug 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.drug import Drug
from app.schemas.drug import DrugResponse, DrugSearchResponse

router = APIRouter()


@router.get("/search", response_model=DrugSearchResponse)
async def search_drugs(
    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 drugs by name. Returns paginated results."""
    offset = (page - 1) * size
    base_query = select(Drug).where(Drug.item_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(Drug.item_name))
    items = result.scalars().all()

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


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


@router.get("/by-slug/{slug}", response_model=DrugResponse)
async def get_drug_by_slug(slug: str, db: AsyncSession = Depends(get_db)):
    """Get drug detail by URL slug (for SSG pages)."""
    result = await db.execute(select(Drug).where(Drug.slug == slug))
    drug = result.scalar_one_or_none()
    if not drug:
        raise HTTPException(status_code=404, detail="Drug not found")
    return drug
