from typing import Annotated
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.audit import log_audit
from app.core.settings_manager import SettingsManager
from app.models.user import User
from app.schemas.admin import SettingsResponse, SettingsUpdate
from app.api.deps import require_admin

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


@router.get("", response_model=SettingsResponse)
async def list_settings(
    db: Annotated[AsyncSession, Depends(get_db)],
    current_user: Annotated[User, Depends(require_admin)],
):
    """List all platform settings."""
    settings = await SettingsManager.get_all(db, include_sensitive=True)
    return SettingsResponse(settings=settings)


@router.put("", response_model=SettingsResponse)
async def update_settings(
    data: SettingsUpdate,
    db: Annotated[AsyncSession, Depends(get_db)],
    current_user: Annotated[User, Depends(require_admin)],
):
    """Update platform settings (batch)."""
    for key, value in data.settings.items():
        await SettingsManager.set(key, value, db, current_user.id)

    await log_audit(db, current_user.id, "settings.update", "platform_settings",
                    details={"keys": list(data.settings.keys())})
    await db.commit()

    settings = await SettingsManager.get_all(db, include_sensitive=True)
    return SettingsResponse(settings=settings)
