# app/api/v1/shop/products.py
"""
Shop Product Catalog API (Public)

Public endpoints for browsing product catalog in shop frontend.
Uses vendor from middleware context (VendorContextMiddleware).
No authentication required.

Vendor Context: require_vendor_context() - detects vendor from URL/subdomain/domain
"""

import logging

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

from app.core.database import get_db
from app.services.product_service import product_service
from middleware.vendor_context import require_vendor_context
from models.database.vendor import Vendor
from models.schema.product import (
    ProductDetailResponse,
    ProductListResponse,
    ProductResponse,
)

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"),
    vendor: Vendor = Depends(require_vendor_context()),
    db: Session = Depends(get_db),
):
    """
    Get product catalog for current vendor.

    Vendor 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"[SHOP_API] get_product_catalog for vendor: {vendor.subdomain}",
        extra={
            "vendor_id": vendor.id,
            "vendor_code": vendor.subdomain,
            "skip": skip,
            "limit": limit,
            "search": search,
            "is_featured": is_featured,
        },
    )

    # Get only active products for public view
    products, total = product_service.get_vendor_products(
        db=db,
        vendor_id=vendor.id,
        skip=skip,
        limit=limit,
        is_active=True,  # Only show active products to customers
        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),
    vendor: Vendor = Depends(require_vendor_context()),
    db: Session = Depends(get_db),
):
    """
    Get detailed product information for customers.

    Vendor 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"[SHOP_API] get_product_details for product {product_id}",
        extra={
            "vendor_id": vendor.id,
            "vendor_code": vendor.subdomain,
            "product_id": product_id,
        },
    )

    product = product_service.get_product(
        db=db, vendor_id=vendor.id, product_id=product_id
    )

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

        raise ProductNotActiveException(str(product_id))

    return ProductDetailResponse.model_validate(product)


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

    Searches in product names, descriptions, and SKUs.
    Vendor 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
    """
    logger.debug(
        f"[SHOP_API] search_products: '{q}'",
        extra={
            "vendor_id": vendor.id,
            "vendor_code": vendor.subdomain,
            "query": q,
            "skip": skip,
            "limit": limit,
        },
    )

    # TODO: Implement full-text search functionality
    # For now, return filtered products
    products, total = product_service.get_vendor_products(
        db=db, vendor_id=vendor.id, skip=skip, limit=limit, is_active=True
    )

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