from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any

from app.core import get_db, get_current_admin_user
from app import services
from app.schemas.catalog_schemas import (
    CategoryCreate, CategoryUpdate, Category,
    ProductCreate, ProductUpdate, Product,
    ProductVariantCreate, ProductVariantUpdate, ProductVariant,
    ProductImageCreate, ProductImageUpdate, ProductImage,
    CollectionCreate, CollectionUpdate, Collection
)
from app.models.user_models import User as UserModel
from app.repositories.catalog_repo import get_products, get_product_by_slug

# Роутер для каталога
catalog_router = APIRouter(prefix="/catalog", tags=["Каталог"])

# Маршруты для коллекций
@catalog_router.post("/collections", response_model=Dict[str, Any])
async def create_collection_endpoint(collection: CollectionCreate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.create_collection(db, collection)


@catalog_router.put("/collections/{collection_id}", response_model=Dict[str, Any])
async def update_collection_endpoint(collection_id: int, collection: CollectionUpdate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.update_collection(db, collection_id, collection)


@catalog_router.delete("/collections/{collection_id}", response_model=Dict[str, Any])
async def delete_collection_endpoint(collection_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.delete_collection(db, collection_id)


@catalog_router.get("/collections", response_model=Dict[str, Any])
async def get_collections_endpoint(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return services.get_collections(db, skip, limit)


@catalog_router.post("/categories", response_model=Dict[str, Any])
async def create_category_endpoint(category: CategoryCreate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.create_category(db, category)


@catalog_router.put("/categories/{category_id}", response_model=Dict[str, Any])
async def update_category_endpoint(category_id: int, category: CategoryUpdate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.update_category(db, category_id, category)


@catalog_router.delete("/categories/{category_id}", response_model=Dict[str, Any])
async def delete_category_endpoint(category_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.delete_category(db, category_id)


@catalog_router.get("/categories", response_model=List[Dict[str, Any]])
async def get_categories_tree(db: Session = Depends(get_db)):
    return services.get_category_tree(db)


@catalog_router.post("/products", response_model=Dict[str, Any])
async def create_product_endpoint(product: ProductCreate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.create_product(db, product)


@catalog_router.put("/products/{product_id}", response_model=Dict[str, Any])
async def update_product_endpoint(product_id: int, product: ProductUpdate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.update_product(db, product_id, product)


@catalog_router.delete("/products/{product_id}", response_model=Dict[str, Any])
async def delete_product_endpoint(product_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.delete_product(db, product_id)


@catalog_router.get("/products/{product_id}", response_model=Dict[str, Any])
async def get_product_details_endpoint(product_id: int, db: Session = Depends(get_db)):
    return services.get_product_details(db, product_id)


@catalog_router.get("/products/slug/{slug}", response_model=Dict[str, Any])
async def get_product_by_slug_endpoint(slug: str, db: Session = Depends(get_db)):
    product = get_product_by_slug(db, slug)
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Продукт не найден"
        )
    return services.get_product_details(db, product.id)


@catalog_router.post("/products/{product_id}/variants", response_model=Dict[str, Any])
async def add_product_variant_endpoint(product_id: int, variant: ProductVariantCreate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    variant.product_id = product_id
    return services.add_product_variant(db, variant)


@catalog_router.put("/variants/{variant_id}", response_model=Dict[str, Any])
async def update_product_variant_endpoint(variant_id: int, variant: ProductVariantUpdate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.update_product_variant(db, variant_id, variant)


@catalog_router.delete("/variants/{variant_id}", response_model=Dict[str, Any])
async def delete_product_variant_endpoint(variant_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.delete_product_variant(db, variant_id)


@catalog_router.post("/products/{product_id}/images", response_model=Dict[str, Any])
async def upload_product_image_endpoint(
    product_id: int, 
    file: UploadFile = File(...), 
    is_primary: bool = Form(False),
    current_user: UserModel = Depends(get_current_admin_user), 
    db: Session = Depends(get_db)
):
    return services.upload_product_image(db, product_id, file, is_primary)


@catalog_router.put("/images/{image_id}", response_model=Dict[str, Any])
async def update_product_image_endpoint(image_id: int, image: ProductImageUpdate, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.update_product_image(db, image_id, image)


@catalog_router.delete("/images/{image_id}", response_model=Dict[str, Any])
async def delete_product_image_endpoint(image_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):
    return services.delete_product_image(db, image_id)


@catalog_router.get("/products", response_model=List[Product])
async def get_products_endpoint(
    skip: int = 0, 
    limit: int = 100, 
    category_id: Optional[int] = None,
    collection_id: Optional[int] = None,
    search: Optional[str] = None,
    min_price: Optional[float] = None,
    max_price: Optional[float] = None,
    is_active: Optional[bool] = True,
    include_variants: Optional[bool] = False,
    db: Session = Depends(get_db)
):
    products = get_products(db, skip, limit, category_id, collection_id, search, min_price, max_price, is_active, include_variants)
    # Преобразуем объекты SQLAlchemy в схемы Pydantic
    return [Product.model_validate(product) for product in products] 