from sqlalchemy.orm import Session, joinedload
from app.models import Product, Category
from app.schemas.product import ProductCreate, ProductUpdate
from typing import List, Optional


def get_products(
    db: Session,
    category_id: Optional[int] = None,
    gender: Optional[str] = None,
    on_sale: Optional[bool] = None,
    featured: Optional[bool] = None,
    skip: int = 0,
    limit: int = 10,
) -> List[Product]:
    query = db.query(Product).options(joinedload(Product.model))

    if category_id:
        query = query.filter(Product.category_id == category_id)
    if gender:
        query = query.filter(Product.gender == gender)
    if on_sale is not None:
        query = query.filter(Product.is_on_sale == on_sale)
    if featured is not None:
        query = query.filter(Product.is_featured == featured)

    return query.offset(skip).limit(limit).all()


def get_product_by_id(db: Session, product_id: int) -> Optional[Product]:
    return db.query(Product).options(joinedload(Product.model)).filter(Product.id == product_id).first()


def create_product(db: Session, product: ProductCreate) -> Product:
    product_data = product.model_dump() if hasattr(product, 'model_dump') else product.dict()
    db_product = Product(**product_data)
    db.add(db_product)
    db.commit()
    db.refresh(db_product)
    return db_product


def update_product(db: Session, product_id: int, product_update: ProductUpdate) -> Optional[Product]:
    db_product = get_product_by_id(db, product_id)
    if not db_product:
        return None

    update_data = product_update.model_dump(exclude_unset=True) if hasattr(product_update, 'model_dump') else product_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_product, field, value)

    db.commit()
    db.refresh(db_product)
    return db_product


def delete_product(db: Session, product_id: int) -> bool:
    db_product = get_product_by_id(db, product_id)
    if not db_product:
        return False

    db.delete(db_product)
    db.commit()
    return True


def search_products(db: Session, query: str, skip: int = 0, limit: int = 10) -> List[Product]:
    return (
        db.query(Product)
        .options(joinedload(Product.model))
        .filter(
            Product.name.ilike(f"%{query}%") | Product.brand.ilike(f"%{query}%")
        )
        .offset(skip)
        .limit(limit)
        .all()
    )
