from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select
from database import get_session
from models import User, UserPreferences
from schemas import UserPreferencesRead, UserPreferencesUpdate
from auth import get_current_user

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

@router.get("/", response_model=UserPreferencesRead)
def read_preferences(
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    prefs = current_user.preferences
    if not prefs:
        # Create default preferences if they don't exist
        prefs = UserPreferences(user_id=current_user.id)
        session.add(prefs)
        session.commit()
        session.refresh(prefs)
    return prefs

@router.put("/", response_model=UserPreferencesRead)
def update_preferences(
    preferences: UserPreferencesUpdate,
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    prefs = current_user.preferences
    if not prefs:
        prefs = UserPreferences(user_id=current_user.id)
        session.add(prefs)
    
    prefs_data = preferences.model_dump(exclude_unset=True)
    for key, value in prefs_data.items():
        setattr(prefs, key, value)
        
    session.add(prefs)
    session.commit()
    session.refresh(prefs)
    return prefs
