"""H5 产品列表 HTTP 接口。"""

from typing import Annotated, Any

from fastapi import APIRouter, Depends, Query, Request
from fastapi.security import HTTPAuthorizationCredentials

from zbt.api.responses import success_response
from zbt.api.v1.h5_auth import bearer_scheme
from zbt.core.errors import AppError
from zbt.domains.catalog.service import ProductCatalogService
from zbt.domains.identity.service import H5AuthService


def create_h5_product_router(
    catalog_service: ProductCatalogService,
    auth_service: H5AuthService,
) -> APIRouter:
    """创建需要 H5 登录身份才能访问的产品路由。"""
    router = APIRouter(tags=["h5-products"])

    def authenticated(
        credentials: Annotated[
            HTTPAuthorizationCredentials | None,
            Depends(bearer_scheme),
        ],
    ) -> None:
        if credentials is None:
            raise AppError("AUTH_REQUIRED", "请先登录", 401)
        auth_service.authenticate_access(credentials.credentials)

    @router.get("/h5/products", dependencies=[Depends(authenticated)])
    def list_products(
        request: Request,
        category: Annotated[str | None, Query(max_length=32)] = None,
    ) -> dict[str, Any]:
        # Query 声明 category 来自 URL 查询参数，例如 ?category=health。
        items = catalog_service.list_available(category=category)
        return success_response(request, {"items": items, "total": len(items)})

    return router
