# app/modules/catalog/routes/pages/storefront.py
"""
Catalog Storefront Page Routes (HTML rendering).

Storefront (customer shop) pages for catalog browsing:
- Shop homepage / product catalog
- Product list
- Product detail
- Category products
- Search results
"""

import logging

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

from app.api.deps import get_db
from app.modules.core.utils.page_context import get_storefront_context
from app.templates_config import templates

logger = logging.getLogger(__name__)

router = APIRouter()


# ============================================================================
# PUBLIC SHOP ROUTES (No Authentication Required)
# ============================================================================


@router.get("/products", response_class=HTMLResponse, include_in_schema=False)
async def shop_products_page(request: Request, db: Session = Depends(get_db)):
    """
    Render product catalog listing.
    Shows featured products and categories.
    """
    logger.debug(
        "[STOREFRONT] shop_products_page REACHED",
        extra={
            "path": request.url.path,
            "store": getattr(request.state, "store", "NOT SET"),
            "context": getattr(request.state, "context_type", "NOT SET"),
        },
    )

    return templates.TemplateResponse(
        "catalog/storefront/products.html", get_storefront_context(request, db=db)
    )


@router.get(
    "/products/{product_id}", response_class=HTMLResponse, include_in_schema=False
)
async def shop_product_detail_page(
    request: Request,
    product_id: int = Path(..., description="Product ID"),
    db: Session = Depends(get_db),
):
    """
    Render product detail page.
    Shows product information, images, reviews, and buy options.
    """
    logger.debug(
        "[STOREFRONT] shop_product_detail_page REACHED",
        extra={
            "path": request.url.path,
            "product_id": product_id,
            "store": getattr(request.state, "store", "NOT SET"),
            "context": getattr(request.state, "context_type", "NOT SET"),
        },
    )

    return templates.TemplateResponse(
        "catalog/storefront/product.html",
        get_storefront_context(request, db=db, product_id=product_id),
    )


@router.get(
    "/categories/{category_slug}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def shop_category_page(
    request: Request,
    category_slug: str = Path(..., description="Category slug"),
    db: Session = Depends(get_db),
):
    """
    Render category products page.
    Shows all products in a specific category.
    """
    logger.debug(
        "[STOREFRONT] shop_category_page REACHED",
        extra={
            "path": request.url.path,
            "category_slug": category_slug,
            "store": getattr(request.state, "store", "NOT SET"),
            "context": getattr(request.state, "context_type", "NOT SET"),
        },
    )

    return templates.TemplateResponse(
        "catalog/storefront/category.html",
        get_storefront_context(request, db=db, category_slug=category_slug),
    )


@router.get("/search", response_class=HTMLResponse, include_in_schema=False)
async def shop_search_page(request: Request, db: Session = Depends(get_db)):
    """
    Render search results page.
    Shows products matching search query.
    """
    logger.debug(
        "[STOREFRONT] shop_search_page REACHED",
        extra={
            "path": request.url.path,
            "store": getattr(request.state, "store", "NOT SET"),
            "context": getattr(request.state, "context_type", "NOT SET"),
        },
    )

    return templates.TemplateResponse(
        "catalog/storefront/search.html", get_storefront_context(request, db=db)
    )


# ============================================================================
# CUSTOMER ACCOUNT - WISHLIST
# ============================================================================


@router.get(
    "/account/wishlist", response_class=HTMLResponse, include_in_schema=False
)
async def shop_wishlist_page(
    request: Request,
    db: Session = Depends(get_db),
):
    """
    Render customer wishlist page.
    View and manage saved products.
    Requires customer authentication (handled by middleware/template).
    """
    from app.api.deps import get_current_customer_from_cookie_or_header

    # Get customer if authenticated
    try:
        current_customer = await get_current_customer_from_cookie_or_header(
            request=request, db=db
        )
    except Exception:
        current_customer = None

    logger.debug(
        "[STOREFRONT] shop_wishlist_page REACHED",
        extra={
            "path": request.url.path,
            "store": getattr(request.state, "store", "NOT SET"),
            "context": getattr(request.state, "context_type", "NOT SET"),
        },
    )

    return templates.TemplateResponse(
        "catalog/storefront/wishlist.html",
        get_storefront_context(request, db=db, user=current_customer),
    )
