# app/modules/catalog/routes/api/storefront.py
"""
Catalog Module - Storefront API Routes

Public endpoints for browsing product catalog in storefront.
Uses store from middleware context (StoreContextMiddleware).
No authentication required.

Store Context: require_store_context() - detects store from URL/subdomain/domain
"""

import logging

from fastapi import APIRouter, Depends, Path, Query, Request
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.modules.catalog.schemas import (
    ProductDetailResponse,
    ProductListResponse,
    ProductResponse,
)
from app.modules.catalog.services import catalog_service
from app.modules.tenancy.models import Store
from middleware.store_context import require_store_context

router = APIRouter()
logger = logging.getLogger(__name__)


@router.get("/products", response_model=ProductListResponse)  # public
def get_product_catalog(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    search: str | None = Query(None, description="Search products by name"),
    is_featured: bool | None = Query(None, description="Filter by featured products"),
    store: Store = Depends(require_store_context()),
    db: Session = Depends(get_db),
):
    """
    Get product catalog for current store.

    Store is automatically determined from request context (URL/subdomain/domain).
    Only returns active products visible to customers.
    No authentication required.

    Query Parameters:
    - skip: Number of products to skip (pagination)
    - limit: Maximum number of products to return
    - search: Search query for product name/description
    - is_featured: Filter by featured products only
    """
    logger.debug(
        f"[CATALOG_STOREFRONT] get_product_catalog for store: {store.subdomain}",
        extra={
            "store_id": store.id,
            "store_code": store.subdomain,
            "skip": skip,
            "limit": limit,
            "search": search,
            "is_featured": is_featured,
        },
    )

    # Get only active products for public view
    products, total = catalog_service.get_catalog_products(
        db=db,
        store_id=store.id,
        skip=skip,
        limit=limit,
        is_featured=is_featured,
    )

    return ProductListResponse(
        products=[ProductResponse.model_validate(p) for p in products],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/products/{product_id}", response_model=ProductDetailResponse)  # public
def get_product_details(
    product_id: int = Path(..., description="Product ID", gt=0),
    store: Store = Depends(require_store_context()),
    db: Session = Depends(get_db),
):
    """
    Get detailed product information for customers.

    Store is automatically determined from request context (URL/subdomain/domain).
    No authentication required.

    Path Parameters:
    - product_id: ID of the product to retrieve
    """
    logger.debug(
        f"[CATALOG_STOREFRONT] get_product_details for product {product_id}",
        extra={
            "store_id": store.id,
            "store_code": store.subdomain,
            "product_id": product_id,
        },
    )

    product = catalog_service.get_product(
        db=db, store_id=store.id, product_id=product_id
    )

    # Check if product is active
    if not product.is_active:
        from app.modules.catalog.exceptions import ProductNotActiveException

        raise ProductNotActiveException(str(product_id))

    return ProductDetailResponse.model_validate(product)


@router.get("/products/search", response_model=ProductListResponse)  # public
def search_products(
    request: Request,
    q: str = Query(..., min_length=1, description="Search query"),
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=100),
    store: Store = Depends(require_store_context()),
    db: Session = Depends(get_db),
):
    """
    Search products in current store's catalog.

    Searches in product names, descriptions, SKUs, brands, and GTINs.
    Store is automatically determined from request context (URL/subdomain/domain).
    No authentication required.

    Query Parameters:
    - q: Search query string (minimum 1 character)
    - skip: Number of results to skip (pagination)
    - limit: Maximum number of results to return
    """
    # Get preferred language from request (via middleware or default)
    language = getattr(request.state, "language", "en")

    logger.debug(
        f"[CATALOG_STOREFRONT] search_products: '{q}'",
        extra={
            "store_id": store.id,
            "store_code": store.subdomain,
            "query": q,
            "skip": skip,
            "limit": limit,
            "language": language,
        },
    )

    # Search products using the service
    products, total = catalog_service.search_products(
        db=db,
        store_id=store.id,
        query=q,
        skip=skip,
        limit=limit,
        language=language,
    )

    return ProductListResponse(
        products=[ProductResponse.model_validate(p) for p in products],
        total=total,
        skip=skip,
        limit=limit,
    )
