from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.database.database import get_db
from app.models import Wishlist, Product, User
from app.schemas.product import ProductResponse
from app.services.auth import get_current_user

router = APIRouter(prefix="/api/wishlist", tags=["wishlist"])


@router.get("", response_model=List[ProductResponse])
def get_wishlist(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    wishlist_items = (
        db.query(Wishlist).filter(Wishlist.user_id == current_user.id).all()
    )
    products = [
        db.query(Product).filter(Product.id == item.product_id).first()
        for item in wishlist_items
    ]
    return products


@router.post("/{product_id}")
def add_to_wishlist(
    product_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    existing = (
        db.query(Wishlist)
        .filter(Wishlist.user_id == current_user.id, Wishlist.product_id == product_id)
        .first()
    )
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Product already in wishlist",
        )

    wishlist_item = Wishlist(user_id=current_user.id, product_id=product_id)
    db.add(wishlist_item)
    db.commit()
    return {"message": "Product added to wishlist"}


@router.delete("/{product_id}")
def remove_from_wishlist(
    product_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    wishlist_item = (
        db.query(Wishlist)
        .filter(Wishlist.user_id == current_user.id, Wishlist.product_id == product_id)
        .first()
    )
    if not wishlist_item:
        raise HTTPException(status_code=404, detail="Item not in wishlist")

    db.delete(wishlist_item)
    db.commit()
    return {"message": "Product removed from wishlist"}
