from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from auth import get_current_user
from database import get_db
from models import User, UserSettings
from schemas import SettingsOut, SettingsUpdate
from services.quiz_service import quiz_service

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


@router.get("", response_model=SettingsOut)
def get_settings(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    s = quiz_service.get_settings(db, current_user)
    return SettingsOut(
        daily_target=s.daily_target,
        master_required_count=s.master_required_count,
        weak_wrong_threshold=s.weak_wrong_threshold,
    )


@router.patch("", response_model=SettingsOut)
def update_settings(
    data: SettingsUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    s = quiz_service.get_settings(db, current_user)
    if data.daily_target is not None:
        s.daily_target = data.daily_target
    if data.master_required_count is not None:
        s.master_required_count = data.master_required_count
    if data.weak_wrong_threshold is not None:
        s.weak_wrong_threshold = data.weak_wrong_threshold
    db.commit()
    db.refresh(s)
    return SettingsOut(
        daily_target=s.daily_target,
        master_required_count=s.master_required_count,
        weak_wrong_threshold=s.weak_wrong_threshold,
    )
