package com.jeesharp.business.modules.contentsecurity.support;

import com.jeesharp.business.modules.contentsecurity.api.ContentSecurityApi;
import com.jeesharp.business.modules.contentsecurity.dto.ContentCheckRequest;
import com.jeesharp.business.modules.contentsecurity.dto.ContentCheckResult;
import com.jeesharp.business.modules.contentsecurity.dto.ContentMemberSnapshot;
import com.jeesharp.business.modules.contentsecurity.dto.ContentSecurityBizRef;
import com.jeesharp.business.modules.contentsecurity.dto.ContentSecurityUgcCheckOutcome;
import com.jeesharp.business.modules.contentsecurity.enums.CheckDecisionEnum;
import com.jeesharp.business.modules.contentsecurity.enums.ContentSceneEnum;
import com.jeesharp.business.modules.contentsecurity.enums.ContentTypeEnum;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * UGC 内容安全检测编排辅助：评价、反馈等模块统一文本+图片检测与 bind 前置收集。
 *
 * @author jeesharp
 * @since 2026-06-27
 */
public final class ContentSecurityUgcCheckSupport {

    private ContentSecurityUgcCheckSupport() {
    }

    /**
     * 同步检测文本与图片；REJECT 时 {@link ContentSecurityApi#assertPass} 抛错。
     */
    public static ContentSecurityUgcCheckOutcome checkTextAndImages(
            ContentSecurityApi api,
            String memberId,
            String tenantId,
            ContentSceneEnum scene,
            ContentSecurityBizRef bizRef,
            String text,
            List<String> imageUrls) {
        return checkTextAndImages(api, memberId, tenantId, scene, bizRef, null, text, imageUrls);
    }

    /**
     * 同步检测文本与图片；REJECT 时 {@link ContentSecurityApi#assertPass} 抛错。
     *
     * @param memberSnapshot 会员摘要冗余，写入检测流水表
     */
    public static ContentSecurityUgcCheckOutcome checkTextAndImages(
            ContentSecurityApi api,
            String memberId,
            String tenantId,
            ContentSceneEnum scene,
            ContentSecurityBizRef bizRef,
            ContentMemberSnapshot memberSnapshot,
            String text,
            List<String> imageUrls) {
        List<String> pendingTraceIds = new ArrayList<>();
        List<String> auditLogIds = new ArrayList<>();
        boolean forcePendingAudit = false;

        if (text != null && !text.isBlank()) {
            ContentCheckResult textResult = api.checkText(ContentCheckRequest.builder()
                    .contentType(ContentTypeEnum.TEXT)
                    .scene(scene)
                    .memberId(memberId)
                    .tenantId(tenantId)
                    .text(text)
                    .bizRef(bizRef)
                    .memberSnapshot(memberSnapshot)
                    .build());
            api.assertPass(textResult);
            mergeSingleResult(textResult, auditLogIds);
            if (needsPendingAudit(textResult.getDecision())) {
                forcePendingAudit = true;
            }
        }

        List<String> normalizedUrls = normalizeImageUrls(imageUrls);
        if (!normalizedUrls.isEmpty()) {
            List<ContentCheckRequest> mediaRequests = new ArrayList<>(normalizedUrls.size());
            for (String url : normalizedUrls) {
                mediaRequests.add(ContentCheckRequest.builder()
                        .contentType(ContentTypeEnum.IMAGE)
                        .scene(scene)
                        .memberId(memberId)
                        .tenantId(tenantId)
                        .mediaUrl(url)
                        .bizRef(bizRef)
                        .memberSnapshot(memberSnapshot)
                        .build());
            }
            ContentCheckResult mediaResult = api.checkMediaBatch(mediaRequests);
            api.assertPass(mediaResult);
            mergeBatchResult(mediaResult, pendingTraceIds, auditLogIds);
            if (needsPendingAudit(mediaResult.getDecision())) {
                forcePendingAudit = true;
            }
        }

        return new ContentSecurityUgcCheckOutcome(forcePendingAudit, pendingTraceIds, auditLogIds);
    }

    /**
     * 业务落库后回绑异步 trace 与同步流水主键。
     */
    public static void bindAfterPersist(
            ContentSecurityApi api, String bizModule, String bizId, ContentSecurityUgcCheckOutcome outcome) {
        if (outcome == null || !outcome.hasBindings()) {
            return;
        }
        api.bindPendingTasks(bizModule, bizId, outcome.pendingTraceIds(), outcome.auditLogIds());
    }

    private static boolean needsPendingAudit(CheckDecisionEnum decision) {
        return decision == CheckDecisionEnum.REVIEW || decision == CheckDecisionEnum.PENDING;
    }

    private static void mergeSingleResult(ContentCheckResult result, List<String> auditLogIds) {
        if (result == null) {
            return;
        }
        String auditLogId = result.getAuditLogId();
        if (auditLogId != null && !auditLogId.isBlank()) {
            auditLogIds.add(auditLogId);
        }
    }

    private static void mergeBatchResult(
            ContentCheckResult result, List<String> pendingTraceIds, List<String> auditLogIds) {
        if (result == null) {
            return;
        }
        if (result.getPendingTraceIds() != null && !result.getPendingTraceIds().isEmpty()) {
            pendingTraceIds.addAll(result.getPendingTraceIds());
        }
        if (result.getAuditLogIds() != null && !result.getAuditLogIds().isEmpty()) {
            auditLogIds.addAll(result.getAuditLogIds());
        }
    }

    private static List<String> normalizeImageUrls(List<String> imageUrls) {
        if (imageUrls == null || imageUrls.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> normalized = new ArrayList<>();
        for (String url : imageUrls) {
            if (url != null && !url.isBlank()) {
                normalized.add(url);
            }
        }
        return normalized;
    }
}
