"""
Product Category API router with CRUD operations.
"""

from typing import List, Optional, Dict, Union, Any
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from src.core.database import get_db
from src.apps.auth.utils.auth import get_current_user
from src.apps.merchants.schemas.merchant_common import MerchantSchema
from src.apps.users.schemas.user_common import UserSchema
from src.apps.product_categories import services
from src.apps.product_categories.schemas.common import (
    ProductCategoryResponseSchema, 
    ProductCategoryCreateSchema, 
    ProductCategoryUpdateSchema,
    ProductCategoryListFilterSchema,
    ProductCategoryBulkDeleteSchema
)
from src.apps.base.utils import regexp
from src.core.utils import constants

router = APIRouter()


@router.get("/", response_model=Dict[str, Any])
async def get_product_categories_list(
    db: Session = Depends(get_db),
    # merchant: MerchantSchema = Depends(get_current_merchant),
    filters: ProductCategoryListFilterSchema = Depends(),
    _from: Optional[str] = Query(
        default=None,
        pattern=regexp.ISO_DATE_FORMAT,
        description="Start date of listing to be done. Must be of format YYYY-MM-DD",
    ),
    _to: Optional[str] = Query(
        default=None,
        pattern=regexp.ISO_DATE_FORMAT,
        description="End date of listing to be done. Must be of format YYYY-MM-DD",
    ),
    sort_by: str = Query(
        default="-created_at",
        description="Sort column name with direction. Prepend '-' to sort descending. E.g: ?sort_by=-created_at",
    ),
    fields: str = Query(
        default=None,
        description="Additional related fields that are requested. Could be any of ...",
    ),
    page: int = Query(
        default=1,
        ge=1,
        description="Number of page that needs to be fetched from the records",
    ),
    per_page: int = Query(
        default=constants.DEFAULT_PER_PAGE,
        ge=1,
        le=constants.MAX_PER_PAGE,
        description="Number of page that needs to be fetched from the records",
    ),
) -> Any:
    """
    Retrieve product categories with filtering and pagination.
    """
    # Calculate offset from page
    skip = (page - 1) * per_page
    
    # Get categories using services
    result = await services.get_product_categories_list(
        db=db,
        filters=filters,
        _from=_from,
        _to=_to,
        sort_by=sort_by,
        fields=fields,
        skip=skip,
        limit=per_page,
        paginate=True,
    )
    
    return result


@router.post("/", response_model=ProductCategoryResponseSchema)
async def create_product_category(
    payload: ProductCategoryCreateSchema,
    db: Session = Depends(get_db),
    # current_merchant: MerchantSchema = Depends(get_current_merchant),
    # current_user: UserSchema = Depends(get_current_user)
):
    """
    Create a new product category.
    """
    return await services.create_product_category(
        db=db, 
        # merchant_id=current_user.id,
        payload=payload
    )


@router.get("/{category_id}", response_model=ProductCategoryResponseSchema)
async def get_product_category(
    category_id: int,
    db: Session = Depends(get_db),
    # current_merchant: MerchantSchema = Depends(get_current_merchant),
    # current_user: UserSchema = Depends(get_current_user)
):
    """
    Get a product category by ID.
    """
    category = await services.get_product_category_by_id(
        db=db, 
        # merchant_id=current_user.id,
        category_id=category_id
    )
    if not category:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product category not found"
        )
    return category


@router.put("/{category_id}", response_model=ProductCategoryResponseSchema)
async def update_product_category(
    category_id: int,
    payload: ProductCategoryUpdateSchema,
    db: Session = Depends(get_db),
    # current_merchant: MerchantSchema = Depends(get_current_merchant),
    # current_user: UserSchema = Depends(get_current_user),
):
    """
    Update a product category by ID.
    """
    updated_category = await services.update_product_category(
        db=db, 
        # merchant_id=current_user.id,
        category_id=category_id, 
        payload=payload
    )
    if not updated_category:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product category not found"
        )
    return updated_category


@router.delete("/{category_id}")
async def delete_product_category(
    category_id: int,
    db: Session = Depends(get_db),
    # current_merchant: MerchantSchema = Depends(get_current_merchant),
    # current_user: UserSchema = Depends(get_current_user)
):
    """
    Delete a product category by ID.
    """
    success = await services.delete_product_category(
        db=db, 
        # merchant_id=current_user.id,
        category_id=category_id
    )
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product category not found"
        )
    return {"message": "Product category deleted successfully"}


@router.post("/bulk-delete")
async def bulk_delete_product_categories(
    bulk_delete_data: ProductCategoryBulkDeleteSchema,
    db: Session = Depends(get_db),
    # current_merchant: MerchantSchema = Depends(get_current_merchant),
    # current_user: UserSchema = Depends(get_current_user)
):
    """
    Delete multiple product categories by IDs.
    """
    deleted_count = await services.bulk_delete_product_categories(
        db=db, 
        # merchant_id=current_user.id,
        category_ids=bulk_delete_data.category_ids
    )
    return {
        "message": f"Successfully deleted {deleted_count} product categories",
        "deleted_count": deleted_count
    }