from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, selectinload

from app.database import get_db
from app.models import Product
from app.schemas import PublicProductOut

router = APIRouter(prefix="/public/catalog", tags=["public-catalog"])


def _serialize(row: Product) -> PublicProductOut:
    return PublicProductOut(
        id=row.id,
        public_id=row.public_id,
        slug=row.slug or row.public_id.lower().replace(" ", "-"),
        name=row.name,
        description=row.description,
        category_name=row.category.name if row.category else None,
        base_price=row.base_price,
        image_url=row.image_url,
        video_url=row.video_url,
    )


@router.get("/products", response_model=list[PublicProductOut])
def list_public_products(db: Session = Depends(get_db)):
    rows = (
        db.query(Product)
        .options(selectinload(Product.category))
        .filter(Product.is_active.is_(True))
        .order_by(Product.name.asc())
        .all()
    )
    return [_serialize(row) for row in rows]


@router.get("/products/{slug}", response_model=PublicProductOut)
def get_public_product(slug: str, db: Session = Depends(get_db)):
    row = (
        db.query(Product)
        .options(selectinload(Product.category))
        .filter(Product.is_active.is_(True), Product.slug == slug)
        .first()
    )
    if row is None:
        # Fallback for older rows / public_id links
        row = (
            db.query(Product)
            .options(selectinload(Product.category))
            .filter(Product.is_active.is_(True), Product.public_id == slug)
            .first()
        )
    if row is None:
        raise HTTPException(status_code=404, detail="Product not found")
    return _serialize(row)
