from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import Dict, Any, List, Optional from app.models.database import get_db from app.services.config_service import ConfigService from app.routes.user import get_current_active_user router = APIRouter(prefix="/config", tags=["config"]) @router.get("/{config_key}") async def get_config( config_key: str, db: Session = Depends(get_db), current_user: dict = Depends(get_current_active_user) ): """获取配置 Args: config_key: 配置键 db: 数据库会话 current_user: 当前活跃用户 Returns: 配置信息 """ config = ConfigService.get_config(db, config_key) if not config: raise HTTPException(status_code=404, detail="配置不存在") return {"key": config_key, "value": config} @router.post("/{config_key}") async def set_config( config_key: str, config_data: Dict[str, Any], db: Session = Depends(get_db), current_user: dict = Depends(get_current_active_user) ): """设置配置 Args: config_key: 配置键 config_data: 配置数据,包含value、type、service_id、description等字段 db: 数据库会话 current_user: 当前活跃用户 Returns: 设置结果 """ success = ConfigService.set_config( db=db, config_key=config_key, config_value=config_data.get("value"), config_type=config_data.get("type", "system"), service_id=config_data.get("service_id"), description=config_data.get("description", "") ) if not success: raise HTTPException(status_code=400, detail="设置配置失败") return {"message": "设置配置成功"} @router.get("/service/{service_id}") async def get_service_configs( service_id: str, db: Session = Depends(get_db), current_user: dict = Depends(get_current_active_user) ): """获取服务配置 Args: service_id: 服务ID db: 数据库会话 current_user: 当前活跃用户 Returns: 服务配置列表 """ configs = ConfigService.get_service_configs(db, service_id) return {"service_id": service_id, "configs": configs} @router.delete("/{config_key}") async def delete_config( config_key: str, db: Session = Depends(get_db), current_user: dict = Depends(get_current_active_user) ): """删除配置 Args: config_key: 配置键 db: 数据库会话 current_user: 当前活跃用户 Returns: 删除结果 """ success = ConfigService.delete_config(db, config_key) if not success: raise HTTPException(status_code=400, detail="删除配置失败") return {"message": "删除配置成功"} @router.get("/") async def get_all_configs( config_type: Optional[str] = None, db: Session = Depends(get_db), current_user: dict = Depends(get_current_active_user) ): """获取所有配置 Args: config_type: 配置类型,可选 db: 数据库会话 current_user: 当前活跃用户 Returns: 配置列表 """ configs = ConfigService.get_all_configs(db, config_type) return {"configs": configs}