package com.zioinfo.esn.ai.controller;

import com.zioinfo.esn.ai.dto.FeedbackRequest;
import com.zioinfo.esn.ai.service.LearningStore;
import com.zioinfo.esn.ai.service.RagFeedbackClient;
import com.zioinfo.esn.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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;

import java.util.Map;

/**
 * AI 답변 피드백 수집(인증 사용자). [ZIOINFO-ESN]
 *
 * <p>👍/👎(+교정)를 ① 로컬 DuckDB({@link LearningStore}) 기록 ② 중앙 guardia-rag({@link RagFeedbackClient})
 * 전달 — 둘 다 수행한다. PII 는 로컬 저장 시 마스킹되며, 중앙 전달분도 마스킹 후 전송한다.
 *
 * <ul><li>POST /api/ai/feedback  피드백 1건 저장(로컬+중앙)</li></ul>
 */
@RestController
@RequestMapping("/api/ai/feedback")
@RequiredArgsConstructor
public class AiFeedbackController {

    private final LearningStore learningStore;
    private final RagFeedbackClient ragClient;

    @PostMapping
    public ApiResponse<Map<String, Object>> submit(@RequestBody FeedbackRequest req) {
        String user = currentActor();
        // 로컬 DuckDB (마스킹은 LearningStore 내부에서 수행).
        learningStore.saveFeedback(req.feature(), req.question(), req.answer(),
                req.verdict(), req.correction(), user);
        // 중앙 rag 전달 — 마스킹 후 전송(로컬과 동일 정책).
        ragClient.forward(req.feature(),
                LearningStore.mask(req.question()),
                LearningStore.mask(req.answer()),
                req.verdict(),
                LearningStore.mask(req.correction()));
        return ApiResponse.ok(Map.of("stored", true, "local", learningStore.isEnabled()));
    }

    private static String currentActor() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        return (a != null && a.getName() != null) ? a.getName() : "anonymous";
    }
}
