# app/modules/catalog/routes/api/store.py
"""
Store product catalog management endpoints.

Store Context: Uses token_store_id from JWT token (authenticated store API pattern).
The get_current_store_api dependency guarantees token_store_id is present.

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

import logging

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

from app.api.deps import get_current_store_api, require_module_access
from app.core.database import get_db
from app.modules.billing.services.subscription_service import subscription_service
from app.modules.catalog.schemas import (
    ProductCreate,
    ProductDeleteResponse,
    ProductDetailResponse,
    ProductListResponse,
    ProductResponse,
    ProductToggleResponse,
    ProductUpdate,
    StoreDirectProductCreate,
    StoreProductCreateResponse,
)
from app.modules.catalog.services.product_service import product_service
from app.modules.catalog.services.store_product_service import store_product_service
from app.modules.enums import FrontendType
from app.modules.tenancy.schemas.auth import UserContext

router = APIRouter(
    prefix="/products",
    dependencies=[Depends(require_module_access("catalog", FrontendType.STORE))],
)
logger = logging.getLogger(__name__)


@router.get("", response_model=ProductListResponse)
def get_store_products(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    is_active: bool | None = Query(None),
    is_featured: bool | None = Query(None),
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Get all products in store catalog.

    Supports filtering by:
    - is_active: Filter active/inactive products
    - is_featured: Filter featured products

    Store is determined from JWT token (store_id claim).
    """
    products, total = product_service.get_store_products(
        db=db,
        store_id=current_user.token_store_id,
        skip=skip,
        limit=limit,
        is_active=is_active,
        is_featured=is_featured,
    )

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


@router.get("/{product_id}", response_model=ProductDetailResponse)
def get_product_details(
    product_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get detailed product information including inventory."""
    product = product_service.get_product(
        db=db, store_id=current_user.token_store_id, product_id=product_id
    )

    return ProductDetailResponse.model_validate(product)


@router.post("", response_model=ProductResponse)
def add_product_to_catalog(
    product_data: ProductCreate,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Add a product from marketplace to store catalog.

    This publishes a MarketplaceProduct to the store's public catalog.
    """
    # Check product limit before creating
    subscription_service.check_product_limit(db, current_user.token_store_id)

    product = product_service.create_product(
        db=db, store_id=current_user.token_store_id, product_data=product_data
    )
    db.commit()

    logger.info(
        f"Product {product.id} added to catalog by user {current_user.username} "
        f"for store {current_user.token_store_code}"
    )

    return ProductResponse.model_validate(product)


@router.post("/create", response_model=StoreProductCreateResponse)
def create_product_direct(
    product_data: StoreDirectProductCreate,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Create a new product directly without marketplace product.

    This creates a Product and ProductTranslation without requiring
    an existing MarketplaceProduct.
    """
    # Check product limit before creating
    subscription_service.check_product_limit(db, current_user.token_store_id)

    # Build data dict with store_id from token
    data = {
        "store_id": current_user.token_store_id,
        "title": product_data.title,
        "brand": product_data.brand,
        "store_sku": product_data.store_sku,
        "gtin": product_data.gtin,
        "price": product_data.price,
        "currency": product_data.currency,
        "availability": product_data.availability,
        "is_active": product_data.is_active,
        "is_featured": product_data.is_featured,
        "description": product_data.description,
    }

    product = store_product_service.create_product(db=db, data=data)
    db.commit()

    logger.info(
        f"Product {product.id} created by user {current_user.username} "
        f"for store {current_user.token_store_code}"
    )

    return StoreProductCreateResponse(
        id=product.id,
        message="Product created successfully",
    )


@router.put("/{product_id}", response_model=ProductResponse)
def update_product(
    product_id: int,
    product_data: ProductUpdate,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Update product in store catalog."""
    product = product_service.update_product(
        db=db,
        store_id=current_user.token_store_id,
        product_id=product_id,
        product_update=product_data,
    )
    db.commit()

    logger.info(
        f"Product {product_id} updated by user {current_user.username} "
        f"for store {current_user.token_store_code}"
    )

    return ProductResponse.model_validate(product)


@router.delete("/{product_id}", response_model=ProductDeleteResponse)
def remove_product_from_catalog(
    product_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Remove product from store catalog."""
    product_service.delete_product(
        db=db, store_id=current_user.token_store_id, product_id=product_id
    )
    db.commit()

    logger.info(
        f"Product {product_id} removed from catalog by user {current_user.username} "
        f"for store {current_user.token_store_code}"
    )

    return ProductDeleteResponse(message=f"Product {product_id} removed from catalog")


@router.post("/from-import/{marketplace_product_id}", response_model=ProductResponse)
def publish_from_marketplace(
    marketplace_product_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Publish a marketplace product to store catalog.

    Shortcut endpoint for publishing directly from marketplace import.
    """
    # Check product limit before creating
    subscription_service.check_product_limit(db, current_user.token_store_id)

    product_data = ProductCreate(
        marketplace_product_id=marketplace_product_id, is_active=True
    )

    product = product_service.create_product(
        db=db, store_id=current_user.token_store_id, product_data=product_data
    )
    db.commit()

    logger.info(
        f"Marketplace product {marketplace_product_id} published to catalog "
        f"by user {current_user.username} for store {current_user.token_store_code}"
    )

    return ProductResponse.model_validate(product)


@router.put("/{product_id}/toggle-active", response_model=ProductToggleResponse)
def toggle_product_active(
    product_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Toggle product active status."""
    product = product_service.get_product(db, current_user.token_store_id, product_id)

    product.is_active = not product.is_active
    db.commit()
    db.refresh(product)

    status = "activated" if product.is_active else "deactivated"
    logger.info(
        f"Product {product_id} {status} for store {current_user.token_store_code}"
    )

    return ProductToggleResponse(
        message=f"Product {status}", is_active=product.is_active
    )


@router.put("/{product_id}/toggle-featured", response_model=ProductToggleResponse)
def toggle_product_featured(
    product_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Toggle product featured status."""
    product = product_service.get_product(db, current_user.token_store_id, product_id)

    product.is_featured = not product.is_featured
    db.commit()
    db.refresh(product)

    status = "featured" if product.is_featured else "unfeatured"
    logger.info(
        f"Product {product_id} {status} for store {current_user.token_store_code}"
    )

    return ProductToggleResponse(
        message=f"Product {status}", is_featured=product.is_featured
    )
