package com.zioinfo.cms.ugc;

import com.zioinfo.cms.admin.AuditService;
import com.zioinfo.cms.ai.AiService;
import com.zioinfo.cms.common.CryptoUtil;
import com.zioinfo.cms.integration.ItsmClient;
import com.zioinfo.cms.ugc.mapper.UgcMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * UGC 서비스 — 작성 시 AI 모더레이션 자동 분류 + 모더레이션 큐 + 문의→ITSM SR + 리뷰 감성.
 *
 * <p>보안: authorEmail(PII)는 암호화 저장, 응답은 마스킹. 위험도 ≥0.7은 자동 REJECT,
 * ≥0.3은 REVIEW(큐), 그 외 APPROVE.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UgcService {

    private final UgcMapper mapper;
    private final AiService aiService;
    private final ItsmClient itsmClient;
    private final CryptoUtil crypto;
    private final AuditService auditService;

    public List<CmsUgc> list(String ugcType, String moderationStatus, Long targetContentId) {
        List<CmsUgc> all = mapper.findAll(ugcType, moderationStatus, targetContentId);
        all.forEach(this::maskEmail);
        return all;
    }

    /** 모더레이션 큐 — PENDING 항목. */
    public List<CmsUgc> queue() {
        List<CmsUgc> all = mapper.findAll(null, "PENDING", null);
        all.forEach(this::maskEmail);
        return all;
    }

    public CmsUgc get(Long id) {
        CmsUgc u = mapper.findById(id);
        if (u == null) throw new RuntimeException("ERR-CMS-UGC-404: UGC 없음");
        return maskEmail(u);
    }

    /** 공개 작성 (인증 불필요 경로에서도 호출 가능). AI 모더레이션 자동 수행. */
    public CmsUgc create(Map<String, Object> req) {
        CmsUgc u = new CmsUgc();
        u.setUgcType(req.get("ugcType") == null ? "COMMENT" : str(req.get("ugcType")));
        u.setTargetContentId(longOf(req.get("targetContentId")));
        u.setTargetRef(str(req.get("targetRef")));
        u.setParentId(longOf(req.get("parentId")));
        u.setAuthorName(req.get("authorName") == null ? "익명" : str(req.get("authorName")));
        // PII 암호화 저장
        String email = str(req.get("authorEmail"));
        u.setAuthorEmail(email == null ? null : crypto.encrypt(email));
        u.setBody(str(req.get("body")));
        u.setRating(intOf(req.get("rating")));

        // AI 모더레이션
        Map<String, Object> mod = aiService.moderate(u.getBody());
        String decision = String.valueOf(mod.get("decision"));
        double risk = toDouble(mod.get("risk"));
        u.setAiRisk(risk);
        u.setAiReason(String.valueOf(mod.getOrDefault("reason", "")));
        u.setModerationStatus(switch (decision) {
            case "REJECT" -> "REJECTED";
            case "APPROVE" -> "APPROVED";
            default -> "PENDING";
        });

        // 리뷰 감성
        if ("REVIEW".equalsIgnoreCase(u.getUgcType()) && u.getBody() != null) {
            double s = aiService.sentimentScore(u.getBody());
            u.setSentiment(s >= 0.6 ? "POSITIVE" : s <= 0.4 ? "NEGATIVE" : "NEUTRAL");
        }
        mapper.insert(u);

        // 문의 → ITSM SR 자동 생성
        if ("INQUIRY".equalsIgnoreCase(u.getUgcType())) {
            String srId = itsmClient.createSr(
                "[CMS 문의] " + (u.getAuthorName()),
                u.getBody(),
                "MEDIUM");
            if (srId != null) {
                mapper.updateSrId(u.getId(), srId);
                u.setItsmSrId(srId);
            }
        }
        auditService.log("system", "UGC_CREATE", u.getUgcType(), "moderation=" + u.getModerationStatus());
        return maskEmail(mapper.findById(u.getId()));
    }

    /** 모더레이터 승인/반려. */
    public CmsUgc moderate(Long id, String status, String reason) {
        CmsUgc u = mapper.findById(id);
        if (u == null) throw new RuntimeException("ERR-CMS-UGC-404: UGC 없음");
        String s = status == null ? "" : status.toUpperCase();
        if (!s.equals("APPROVED") && !s.equals("REJECTED")) {
            throw new IllegalArgumentException("ERR-CMS-UGC-400: status는 APPROVED/REJECTED");
        }
        mapper.updateModeration(id, s, u.getAiRisk(), reason == null ? u.getAiReason() : reason);
        auditService.log("UGC_MODERATE", String.valueOf(id), u.getModerationStatus() + " -> " + s);
        return maskEmail(mapper.findById(id));
    }

    /** 리뷰 AI 요약 — 대상의 승인 리뷰들 요약/감성. */
    public Map<String, Object> reviewSummary(String targetRef) {
        List<CmsUgc> reviews = mapper.findApprovedReviews(targetRef);
        List<String> bodies = reviews.stream().map(CmsUgc::getBody).filter(b -> b != null).toList();
        return aiService.reviewSummary(bodies);
    }

    public void delete(Long id) {
        get(id);
        mapper.delete(id);
        auditService.log("UGC_DELETE", String.valueOf(id), null);
    }

    // ── helpers ──
    private CmsUgc maskEmail(CmsUgc u) {
        if (u.getAuthorEmail() != null) {
            String dec = crypto.decrypt(u.getAuthorEmail());
            u.setAuthorEmail(CryptoUtil.mask(dec));
        }
        return u;
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
    private Long longOf(Object o) { if (o == null) return null; try { return Long.valueOf(String.valueOf(o).trim()); } catch (Exception e) { return null; } }
    private Integer intOf(Object o) { if (o == null) return null; try { return Integer.valueOf(String.valueOf(o).trim()); } catch (Exception e) { return null; } }
    private double toDouble(Object o) { if (o == null) return 0; try { return Double.parseDouble(String.valueOf(o)); } catch (Exception e) { return 0; } }
}
