"""
Admin API - Settings Routes

包含系统设置相关的 API 路由。
"""

import logging

from fastapi import APIRouter, Depends

from src.auth.dependencies import require_admin
from src.auth.models import UserAuth
from src.models.schemas import ResponseModel
from src.models.admin_schemas import SystemSettingUpdateRequest
from src.services.admin_service import admin_service
from src.utils.errors import ErrorCode, AppException

logger = logging.getLogger(__name__)

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


@router.get("", response_model=ResponseModel)
async def get_system_settings(
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Get system settings

    Returns all configurable system settings.
    Requires admin privileges.
    """
    try:
        settings = await admin_service.get_system_settings()
        return ResponseModel(data=settings.model_dump())
    except Exception as e:
        logger.error(f"Error getting system settings: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )


@router.put("/{key}", response_model=ResponseModel)
async def update_system_setting(
    key: str,
    request: SystemSettingUpdateRequest,
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Update a system setting

    Requires admin privileges.
    """
    try:
        setting = await admin_service.update_system_setting(key, request.value)
        if not setting:
            raise AppException(
                code=ErrorCode.NOT_FOUND,
                message="Setting not found",
                status_code=404
            )

        return ResponseModel(
            data={
                "key": key,
                "value": request.value,
                "updated_at": setting.updated_at,
                "message": "Setting updated successfully",
            }
        )
    except AppException:
        raise
    except Exception as e:
        logger.error(f"Error updating system setting: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )
