from fastapi import APIRouter, Depends, Query, File, UploadFile, status
from sqlalchemy.orm import Session
from typing import Optional, List
import uuid
from app.api import deps
from app.db.session import get_db
from app.schemas.product import ProductCreate, ProductUpdate, ProductResponse, ProductListResponse
from app.schemas.category import CategoryCreate, CategoryResponse
from app.services.product import product_service
from app.utils.storage import storage_helper
from app.core.exceptions import BadRequestException

router = APIRouter()

# --- CATEGORY ENDPOINTS ---
@router.post("/categories", response_model=CategoryResponse, status_code=status.HTTP_201_CREATED)
def create_category(
    category_in: CategoryCreate,
    db: Session = Depends(get_db),
    current_admin: Session = Depends(deps.get_current_active_superuser)
):
    """Admin-only endpoint to add new product categories."""
    return product_service.create_category(db, name=category_in.name, description=category_in.description)

@router.get("/categories", response_model=List[CategoryResponse])
def get_categories(
    db: Session = Depends(get_db)
):
    """Retrieve all categories (public)."""
    return product_service.list_categories(db)


# --- PRODUCT ENDPOINTS ---
@router.get("/products", response_model=ProductListResponse)
def get_products(
    db: Session = Depends(get_db),
    search: Optional[str] = Query(None, description="Search product by name or description"),
    material: Optional[str] = Query(None, description="Filter material: titanium or xuping"),
    category_id: Optional[str] = Query(None, description="Filter category ID"),
    sort_by: Optional[str] = Query("created_at", description="Sort fields: price, created_at"),
    sort_order: Optional[str] = Query("desc", description="Sort order: asc, desc"),
    skip: int = Query(0, ge=0),
    limit: int = Query(12, ge=1, le=100)
):
    """Retrieve list of active products with custom query params (public)."""
    products, total = product_service.list_products(
        db,
        search=search,
        material=material,
        category_id=category_id,
        sort_by=sort_by,
        sort_order=sort_order,
        skip=skip,
        limit=limit
    )
    return {
        "success": True,
        "data": products,
        "total": total,
        "skip": skip,
        "limit": limit
    }

@router.get("/products/{slug_or_id}", response_model=ProductResponse)
def get_product(
    slug_or_id: str,
    db: Session = Depends(get_db)
):
    """Get detailed specifications of a product using either ID or slug (public)."""
    # Cek apakah parameter input bertipe UUID valid, jika bukan cari via slug
    try:
        uuid.UUID(slug_or_id)
        return product_service.get_product(db, product_id=slug_or_id)
    except ValueError:
        return product_service.get_product_by_slug(db, slug=slug_or_id)

@router.post("/products", response_model=ProductResponse, status_code=status.HTTP_201_CREATED)
def create_product(
    product_in: ProductCreate,
    db: Session = Depends(get_db),
    current_admin: Session = Depends(deps.get_current_active_superuser)
):
    """Admin-only endpoint to register a new product item."""
    return product_service.create_product(
        db,
        name=product_in.name,
        description=product_in.description,
        price=product_in.price,
        stock=product_in.stock,
        material=product_in.material,
        category_id=str(product_in.category_id)
    )

@router.post("/products/upload-image")
async def upload_product_image(
    file: UploadFile = File(...),
    current_admin: Session = Depends(deps.get_current_active_superuser)
):
    """Admin-only endpoint to upload product photos to storage server."""
    if not storage_helper:
        raise BadRequestException("Storage client is not configured on this server.")
        
    contents = await file.read()
    file_url = storage_helper.upload_file(
        file_data=contents,
        filename=file.filename,
        content_type=file.content_type
    )
    
    if not file_url:
        raise BadRequestException("Failed saving image file.")
        
    return {"url": file_url}

@router.put("/products/{product_id}", response_model=ProductResponse)
def update_product(
    product_id: uuid.UUID,
    product_in: ProductUpdate,
    db: Session = Depends(get_db),
    current_admin: Session = Depends(deps.get_current_active_superuser)
):
    """Admin-only endpoint to update product info."""
    update_data = product_in.model_dump(exclude_unset=True)
    return product_service.update_product(db, product_id=str(product_id), obj_in=update_data)

@router.delete("/products/{product_id}", response_model=ProductResponse)
def delete_product(
    product_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_admin: Session = Depends(deps.get_current_active_superuser)
):
    """Admin-only endpoint to soft delete a product item."""
    return product_service.soft_delete_product(db, product_id=str(product_id))
