# app/modules/marketplace/routes/api/admin_products.py
"""
Admin marketplace product catalog endpoints.

Provides platform-wide product search and management capabilities:
- Browse all marketplace products across stores
- Search by title, GTIN, SKU, brand
- Filter by marketplace, store, availability, product type
- View product details and translations
- Copy products to store catalogs

All routes require module access control for the 'marketplace' module.
"""

import logging

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

from app.api.deps import get_current_admin_api, require_module_access
from app.core.database import get_db
from app.modules.enums import FrontendType
from app.modules.marketplace.services.marketplace_product_service import (
    marketplace_product_service,
)
from app.modules.tenancy.schemas.auth import UserContext

admin_products_router = APIRouter(
    prefix="/products",
    dependencies=[Depends(require_module_access("marketplace", FrontendType.ADMIN))],
)
logger = logging.getLogger(__name__)


# ============================================================================
# Pydantic Models
# ============================================================================


class AdminProductListItem(BaseModel):
    """Product item for admin list view."""

    id: int
    marketplace_product_id: str
    title: str | None = None
    brand: str | None = None
    gtin: str | None = None
    sku: str | None = None
    marketplace: str | None = None
    store_name: str | None = None
    price_numeric: float | None = None
    currency: str | None = None
    availability: str | None = None
    image_link: str | None = None
    is_active: bool | None = None
    is_digital: bool | None = None
    product_type_enum: str | None = None
    created_at: str | None = None
    updated_at: str | None = None

    class Config:
        from_attributes = True


class AdminProductListResponse(BaseModel):
    """Paginated product list response for admin."""

    products: list[AdminProductListItem]
    total: int
    skip: int
    limit: int


class AdminProductStats(BaseModel):
    """Product statistics for admin dashboard."""

    total: int
    active: int
    inactive: int
    digital: int
    physical: int
    by_marketplace: dict[str, int]


class MarketplacesResponse(BaseModel):
    """Response for marketplaces list."""

    marketplaces: list[str]


class StoresResponse(BaseModel):
    """Response for stores list."""

    stores: list[str]


class CopyToStoreRequest(BaseModel):
    """Request body for copying products to store catalog."""

    marketplace_product_ids: list[int]
    store_id: int
    skip_existing: bool = True


class CopyToStoreResponse(BaseModel):
    """Response from copy to store operation."""

    copied: int
    skipped: int
    failed: int
    auto_matched: int = 0
    limit_reached: bool = False
    details: list[dict] | None = None


class AdminProductDetail(BaseModel):
    """Detailed product information for admin view."""

    id: int
    marketplace_product_id: str | None = None
    gtin: str | None = None
    mpn: str | None = None
    sku: str | None = None
    brand: str | None = None
    marketplace: str | None = None
    store_name: str | None = None
    source_url: str | None = None
    price: str | None = None
    price_numeric: float | None = None
    sale_price: str | None = None
    sale_price_numeric: float | None = None
    currency: str | None = None
    availability: str | None = None
    condition: str | None = None
    image_link: str | None = None
    additional_images: list | None = None
    is_active: bool | None = None
    is_digital: bool | None = None
    product_type_enum: str | None = None
    platform: str | None = None
    google_product_category: str | None = None
    category_path: str | None = None
    color: str | None = None
    size: str | None = None
    weight: float | None = None
    weight_unit: str | None = None
    translations: dict | None = None
    created_at: str | None = None
    updated_at: str | None = None


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


@admin_products_router.get("", response_model=AdminProductListResponse)
def get_products(
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=500),
    search: str | None = Query(
        None, description="Search by title, GTIN, SKU, or brand"
    ),
    marketplace: str | None = Query(None, description="Filter by marketplace"),
    store_name: str | None = Query(None, description="Filter by store name"),
    availability: str | None = Query(None, description="Filter by availability"),
    is_active: bool | None = Query(None, description="Filter by active status"),
    is_digital: bool | None = Query(None, description="Filter by digital products"),
    language: str = Query("en", description="Language for title lookup"),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Get all marketplace products with search and filtering.

    This endpoint allows admins to browse the entire product catalog
    imported from various marketplaces.
    """
    products, total = marketplace_product_service.get_admin_products(
        db=db,
        skip=skip,
        limit=limit,
        search=search,
        marketplace=marketplace,
        store_name=store_name,
        availability=availability,
        is_active=is_active,
        is_digital=is_digital,
        language=language,
    )

    return AdminProductListResponse(
        products=[AdminProductListItem(**p) for p in products],
        total=total,
        skip=skip,
        limit=limit,
    )


@admin_products_router.get("/stats", response_model=AdminProductStats)
def get_product_stats(
    marketplace: str | None = Query(None, description="Filter by marketplace"),
    store_name: str | None = Query(None, description="Filter by store name"),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get product statistics for admin dashboard."""
    stats = marketplace_product_service.get_admin_product_stats(
        db, marketplace=marketplace, store_name=store_name
    )
    return AdminProductStats(**stats)


@admin_products_router.get("/marketplaces", response_model=MarketplacesResponse)
def get_marketplaces(
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get list of unique marketplaces in the product catalog."""
    marketplaces = marketplace_product_service.get_marketplaces_list(db)
    return MarketplacesResponse(marketplaces=marketplaces)


@admin_products_router.get("/stores", response_model=StoresResponse)
def get_product_stores(
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get list of unique store names in the product catalog."""
    stores = marketplace_product_service.get_source_stores_list(db)
    return StoresResponse(stores=stores)


@admin_products_router.post("/copy-to-store", response_model=CopyToStoreResponse)
def copy_products_to_store(
    request: CopyToStoreRequest,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Copy marketplace products to a store's catalog.

    This endpoint allows admins to copy products from the master marketplace
    product repository to any store's product catalog.

    The copy creates a new Product entry linked to the MarketplaceProduct,
    with default values that can be overridden by the store later.
    """
    result = marketplace_product_service.copy_to_store_catalog(
        db=db,
        marketplace_product_ids=request.marketplace_product_ids,
        store_id=request.store_id,
        skip_existing=request.skip_existing,
    )
    db.commit()
    return CopyToStoreResponse(**result)


@admin_products_router.get("/{product_id}", response_model=AdminProductDetail)
def get_product_detail(
    product_id: int,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get detailed product information including all translations."""
    product = marketplace_product_service.get_admin_product_detail(db, product_id)
    return AdminProductDetail(**product)
