from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select
from database import get_session
from models import User, UserBadge, Badge
from schemas import UserBadgeRead
from auth import get_current_user
from services.stats import check_and_award_badges

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

@router.get("/me", response_model=List[UserBadgeRead])
def read_my_badges(
    session: Session = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    # Trigger a check (lazy evaluation of badges)
    check_and_award_badges(session, current_user.id)
    
    # Refresh user to get new badges
    session.refresh(current_user)
    return current_user.badges

@router.get("/{user_id}", response_model=List[UserBadgeRead])
def read_user_badges(
    user_id: int,
    session: Session = Depends(get_session)
):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user.badges
