"""Site settings API endpoints."""

from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, verify_api_key
from app.models.models import SiteSetting

router = APIRouter()


@router.get("/")
async def list_settings(db: AsyncSession = Depends(get_db)):
    """List all site settings."""
    result = await db.execute(select(SiteSetting))
    settings = result.scalars().all()
    return {s.key: s.value for s in settings}


@router.patch("/")
async def update_settings(
    updates: dict[str, str],
    db: AsyncSession = Depends(get_db),
    api_key: str = Depends(verify_api_key),
):
    """Update site settings (key-value pairs)."""
    for key, value in updates.items():
        result = await db.execute(select(SiteSetting).where(SiteSetting.key == key))
        setting = result.scalar_one_or_none()
        if setting:
            setting.value = value
        else:
            db.add(SiteSetting(key=key, value=value))
    await db.flush()
    return {"message": "Settings updated"}