package com.zioinfo.hrm.ai.controller;

import com.zioinfo.hrm.ai.dto.FeedbackRequest;
import com.zioinfo.hrm.ai.learning.CentralFeedbackForwarder;
import com.zioinfo.hrm.ai.learning.LearningStore;
import com.zioinfo.hrm.ai.learning.PiiMasker;
import com.zioinfo.hrm.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
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.LinkedHashMap;
import java.util.Map;

/**
 * AI 답변 피드백 수집(인증 사용자). [GUARDiA-HRM]
 *
 * <p>{@code POST /api/hrm/ai/feedback} — 👍/👎 + 교정문을 ①로컬 DuckDB({@link LearningStore}) 적재 +
 * ②중앙 guardia-rag {@code /feedback} 전달(둘 다). 텍스트는 적재/전달 전 {@link PiiMasker} 로 마스킹된다
 * (인사 데이터 특성상 필수). DuckDB 미가용 시에도 중앙 전달은 시도하며, 어느 쪽 실패도 사용자 흐름을
 * 막지 않는다(무회귀).
 */
@RestController
@RequestMapping("/api/hrm/ai")
@RequiredArgsConstructor
public class FeedbackController {

    private final LearningStore learningStore;
    private final CentralFeedbackForwarder forwarder;

    @PostMapping("/feedback")
    public ApiResponse<Map<String, Object>> feedback(@RequestBody FeedbackRequest req, Authentication auth) {
        String verdict = normalizeVerdict(req.verdict());
        String user = auth != null ? auth.getName() : "anon";

        // 로컬 DuckDB 적재(내부에서 PII 마스킹).
        boolean stored = learningStore.recordFeedback(
                req.feature(), req.question(), req.answer(), verdict, req.correction(), user);

        // 중앙 rag 전달(마스킹된 값만).
        forwarder.forward(
                req.feature(),
                PiiMasker.mask(req.question()),
                PiiMasker.mask(req.answer()),
                verdict,
                PiiMasker.mask(req.correction()));

        Map<String, Object> out = new LinkedHashMap<>();
        out.put("storedLocal", stored);
        out.put("verdict", verdict);
        return ApiResponse.ok(out);
    }

    private static String normalizeVerdict(String v) {
        if (v == null) {
            return "up";
        }
        String s = v.trim().toLowerCase();
        return "down".equals(s) ? "down" : "up";
    }
}
