package com.zioinfo.kintex.ai.nlquery;

import com.zioinfo.kintex.ai.nlquery.dto.NlQueryDtos.NlQueryRequest;
import com.zioinfo.kintex.ai.nlquery.dto.NlQueryDtos.NlQueryResult;
import com.zioinfo.kintex.ai.nlquery.dto.NlQueryDtos.RulesChatRequest;
import com.zioinfo.kintex.ai.nlquery.dto.NlQueryDtos.RulesChatResult;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.audit.Audited;
import com.zioinfo.kintex.system.SystemAccessGuard;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * F092 자연어 조회(Text-to-SQL) + F025 규정 자연어 챗봇 API (AI 라우터 경유).
 *
 * <ul>
 *   <li>POST /api/ai/nlquery — 자연어 → 안전 SELECT 실행(<b>시스템관리자</b> 전용, 행사 횡단 데이터 접근). @Audited</li>
 *   <li>POST /api/ai/rules-chat — 규정/요율 근거 챗봇(인증 사용자). 근거 없으면 정직 응답.</li>
 * </ul>
 * 두 엔드포인트 모두 산출 출처(provider·degraded)와 근거(생성 SQL / 인용 룰)를 응답에 정직하게 담는다.
 */
@RestController
@RequestMapping("/api/ai")
public class NlQueryController {

    private final NlQueryService nlQueryService;
    private final RulesChatService rulesChatService;
    private final SystemAccessGuard guard;

    public NlQueryController(NlQueryService nlQueryService, RulesChatService rulesChatService,
                             SystemAccessGuard guard) {
        this.nlQueryService = nlQueryService;
        this.rulesChatService = rulesChatService;
        this.guard = guard;
    }

    /** 자연어 조회 — 시스템관리자(홀매니저/ADMIN) 전용. AI 미가용/가드 위반 시 명확한 4xx. */
    @Audited(action = "AI_NLQUERY", targetType = "nlquery")
    @PostMapping("/nlquery")
    public ApiResponse<NlQueryResult> nlquery(@AuthenticationPrincipal KintexPrincipal principal,
                                              @RequestBody NlQueryRequest req) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(nlQueryService.ask(req == null ? null : req.question()));
    }

    /** 규정 챗봇 — 인증 사용자면 열람 가능(규정/요율은 정책 안내 성격). */
    @PostMapping("/rules-chat")
    public ApiResponse<RulesChatResult> rulesChat(@AuthenticationPrincipal KintexPrincipal principal,
                                                  @RequestBody RulesChatRequest req) {
        guard.require(principal);
        return ApiResponse.ok(rulesChatService.chat(req == null ? null : req.question()));
    }
}
