"""System settings routes — get and upsert (admin only)."""

from __future__ import annotations

import uuid

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.db import get_db
from app.deps import require_permission
from app.schemas.system_settings import SystemSettingsUpsert, SystemSettingsResponse
from app.services import system_settings_service

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


@router.get("", response_model=SystemSettingsResponse)
async def get_system_settings(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("settings:read")),
):
    """Get system settings for the current tenant."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    result = await system_settings_service.get_system_settings(db, tenant_id)
    if result is None:
        return SystemSettingsResponse()
    return result


@router.put("", response_model=SystemSettingsResponse)
async def upsert_system_settings(
    body: SystemSettingsUpsert,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("settings:write")),
):
    """Upsert system settings. Requires admin permission."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    data = body.model_dump()
    return await system_settings_service.upsert_system_settings(db, tenant_id, user_id, data)
