from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select
from typing import List
from app.core.database import get_session
from app.models.favorite import Favorite
from app.api.deps import get_current_user
from app.models.user import User
from pydantic import BaseModel

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


class FavoriteCreate(BaseModel):
    item_type: str  # 'coupon', 'business', 'taxi', 'route'
    item_id: str
    item_name: str | None = None
    item_image: str | None = None


@router.get("")
async def get_favorites(
    item_type: str | None = None,
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
) -> List[Favorite]:
    """Get all favorites for the current user, optionally filtered by type."""
    statement = select(Favorite).where(Favorite.user_id == current_user.id)
    
    if item_type:
        statement = statement.where(Favorite.item_type == item_type)
    
    statement = statement.order_by(Favorite.created_at.desc())
    favorites = session.exec(statement).all()
    return list(favorites)


@router.post("")
async def add_favorite(
    favorite_data: FavoriteCreate,
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
) -> Favorite:
    """Add an item to favorites."""
    # Check if already favorited
    existing = session.exec(
        select(Favorite).where(
            Favorite.user_id == current_user.id,
            Favorite.item_type == favorite_data.item_type,
            Favorite.item_id == favorite_data.item_id
        )
    ).first()
    
    if existing:
        raise HTTPException(status_code=400, detail="Item already in favorites")
    
    favorite = Favorite(
        user_id=current_user.id,
        item_type=favorite_data.item_type,
        item_id=favorite_data.item_id,
        item_name=favorite_data.item_name,
        item_image=favorite_data.item_image
    )
    session.add(favorite)
    session.commit()
    session.refresh(favorite)
    return favorite


@router.delete("/{item_type}/{item_id}")
async def remove_favorite(
    item_type: str,
    item_id: str,
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """Remove an item from favorites."""
    favorite = session.exec(
        select(Favorite).where(
            Favorite.user_id == current_user.id,
            Favorite.item_type == item_type,
            Favorite.item_id == item_id
        )
    ).first()
    
    if not favorite:
        raise HTTPException(status_code=404, detail="Favorite not found")
    
    session.delete(favorite)
    session.commit()
    return {"ok": True}


@router.get("/check/{item_type}/{item_id}")
async def check_favorite(
    item_type: str,
    item_id: str,
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
) -> dict:
    """Check if an item is favorited."""
    favorite = session.exec(
        select(Favorite).where(
            Favorite.user_id == current_user.id,
            Favorite.item_type == item_type,
            Favorite.item_id == item_id
        )
    ).first()
    
    return {"is_favorite": favorite is not None}
