# app/api/v1/admin/vendor_products.py
"""
Admin vendor product catalog endpoints.

Provides management of vendor-specific product catalogs:
- Browse products in vendor catalogs
- View product details with override info
- Remove products from catalog

Architecture Notes:
- All Pydantic schemas are defined in models/schema/vendor_product.py
- Business logic is delegated to vendor_product_service
"""

import logging

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

from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.vendor_product_service import vendor_product_service
from models.database.user import User
from models.schema.vendor_product import (
    CatalogVendor,
    CatalogVendorsResponse,
    RemoveProductResponse,
    VendorProductDetail,
    VendorProductListItem,
    VendorProductListResponse,
    VendorProductStats,
)

router = APIRouter(prefix="/vendor-products")
logger = logging.getLogger(__name__)


# ============================================================================
# Endpoints
# ============================================================================


@router.get("", response_model=VendorProductListResponse)
def get_vendor_products(
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=500),
    search: str | None = Query(None, description="Search by title or SKU"),
    vendor_id: int | None = Query(None, description="Filter by vendor"),
    is_active: bool | None = Query(None, description="Filter by active status"),
    is_featured: bool | None = Query(None, description="Filter by featured status"),
    language: str = Query("en", description="Language for title lookup"),
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """
    Get all products in vendor catalogs with filtering.

    This endpoint allows admins to browse products that have been
    copied to vendor catalogs from the marketplace repository.
    """
    products, total = vendor_product_service.get_products(
        db=db,
        skip=skip,
        limit=limit,
        search=search,
        vendor_id=vendor_id,
        is_active=is_active,
        is_featured=is_featured,
        language=language,
    )

    return VendorProductListResponse(
        products=[VendorProductListItem(**p) for p in products],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/stats", response_model=VendorProductStats)
def get_vendor_product_stats(
    vendor_id: int | None = Query(None, description="Filter stats by vendor ID"),
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get vendor product statistics for admin dashboard."""
    stats = vendor_product_service.get_product_stats(db, vendor_id=vendor_id)
    return VendorProductStats(**stats)


@router.get("/vendors", response_model=CatalogVendorsResponse)
def get_catalog_vendors(
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get list of vendors with products in their catalogs."""
    vendors = vendor_product_service.get_catalog_vendors(db)
    return CatalogVendorsResponse(vendors=[CatalogVendor(**v) for v in vendors])


@router.get("/{product_id}", response_model=VendorProductDetail)
def get_vendor_product_detail(
    product_id: int,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get detailed vendor product information including override info."""
    product = vendor_product_service.get_product_detail(db, product_id)
    return VendorProductDetail(**product)


@router.delete("/{product_id}", response_model=RemoveProductResponse)
def remove_vendor_product(
    product_id: int,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Remove a product from vendor catalog."""
    result = vendor_product_service.remove_product(db, product_id)
    db.commit()  # ✅ ARCH: Commit at API level for transaction control
    return RemoveProductResponse(**result)
