from fastapi import APIRouter, Depends
from sqlmodel import Session, select
from app.database import get_session
from app.models.settings import UserSettings

router = APIRouter(tags=["réglages"])


@router.get("/settings")
def get_settings(session: Session = Depends(get_session)):
    rows = session.exec(select(UserSettings)).all()
    return {r.cle: r.valeur for r in rows}


@router.put("/settings")
def update_settings(data: dict, session: Session = Depends(get_session)):
    for cle, valeur in data.items():
        row = session.exec(select(UserSettings).where(UserSettings.cle == cle)).first()
        if row:
            row.valeur = str(valeur)
        else:
            row = UserSettings(cle=cle, valeur=str(valeur))
        session.add(row)
    session.commit()
    return {"ok": True}
