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

from app.api.deps import require_roles
from app.db.session import get_db
from app.models import AdminUser
from app.schemas.setting import PdfSettingsOut, PdfSettingsUpdate
from app.services.logs import log_action
from app.services.system_settings import get_pdf_settings, update_pdf_generation_concurrency_limit

router = APIRouter()


@router.get("/pdf", response_model=PdfSettingsOut)
def get_pdf_generation_settings(
    db: Session = Depends(get_db),
    _: AdminUser = Depends(require_roles("system_admin")),
) -> dict[str, object]:
    settings = get_pdf_settings(db)
    db.commit()
    return settings


@router.put("/pdf", response_model=PdfSettingsOut)
def update_pdf_generation_settings(
    payload: PdfSettingsUpdate,
    db: Session = Depends(get_db),
    admin: AdminUser = Depends(require_roles("system_admin")),
) -> dict[str, object]:
    before = get_pdf_settings(db)
    after = update_pdf_generation_concurrency_limit(db, payload.pdf_generation_concurrency_limit)
    log_action(
        db,
        admin,
        "update_pdf_settings",
        "system_setting",
        "pdf_generation_concurrency_limit",
        detail={
            "before": before["pdf_generation_concurrency_limit"],
            "after": after["pdf_generation_concurrency_limit"],
        },
    )
    db.commit()
    return after
