package com.zioinfo.cms.rag;

import com.zioinfo.cms.admin.SettingService;
import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * CMS 최신 AI 기법(중앙 guardia-rag) 배선 API — 별개 레이어.
 *
 * <ul>
 *   <li>POST /api/cms/rag/content-draft — 콘텐츠 초안(/answer hybrid 또는 /agent, 근거+인용+보류)</li>
 *   <li>POST /api/cms/rag/moderate      — UGC 모더레이션(/structured 결정론 JSON, 애매 시 보류)</li>
 *   <li>POST /api/cms/rag/feedback      — 👍/👎 피드백(/rag/feedback, solution=cms 격리)</li>
 *   <li>GET  /api/cms/rag/toggles       — 현재 기법/신뢰도 토글 스냅샷</li>
 *   <li>PUT  /api/cms/rag/toggles/{key} — 토글 변경(rag.* 키, cms_setting 격리 저장 + 감사로그)</li>
 * </ul>
 *
 * <p>기존 {@code /api/cms/ai/*} 는 불변. 본 컨트롤러는 중앙 경유 신규 경로만 추가한다.
 * RBAC 은 SecurityConfig 통제(GET=Viewer+, POST/PUT=Author+).
 */
@RestController
@RequestMapping("/api/cms/rag")
@RequiredArgsConstructor
public class RagController {

    private final RagCmsService service;
    private final SettingService settingService;

    @PostMapping("/content-draft")
    public ApiResponse<Map<String, Object>> contentDraft(@RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.contentDraft(req, auth == null ? null : auth.getName()));
    }

    @PostMapping("/moderate")
    public ApiResponse<Map<String, Object>> moderate(@RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.moderate(req, auth == null ? null : auth.getName()));
    }

    @PostMapping("/feedback")
    public ApiResponse<Map<String, Object>> feedback(@RequestBody Map<String, Object> req, Authentication auth) {
        return ApiResponse.ok(service.feedback(req, auth == null ? null : auth.getName()));
    }

    @GetMapping("/toggles")
    public ApiResponse<Map<String, Object>> toggles() {
        return ApiResponse.ok(service.currentToggles());
    }

    /**
     * 토글 변경 — 기존 cms_setting upsert(감사로그 자동 기록) 재사용.
     * 허용 키는 {@code rag.*} 네임스페이스로 한정.
     */
    @PutMapping("/toggles/{key}")
    public ApiResponse<Map<String, Object>> updateToggle(@PathVariable String key,
                                                         @RequestBody Map<String, Object> req) {
        if (key == null || !key.startsWith("rag.")) {
            return ApiResponse.fail("ERR-RAG-400: rag.* 키만 변경 가능");
        }
        Object v = req.get("value");
        settingService.update(key, v == null ? "" : String.valueOf(v));
        return ApiResponse.ok(service.currentToggles());
    }
}
