package tech.easyflow.ai.documentimport;

import com.alicp.jetcache.Cache;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.math.BigInteger;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.UUID;

@Service
public class DocumentImportPreviewService {

    private static final Duration SESSION_TTL = Duration.ofMinutes(30);

    private final Cache<String, Object> defaultCache;

    public DocumentImportPreviewService(@Qualifier("defaultCache") Cache<String, Object> defaultCache) {
        this.defaultCache = defaultCache;
    }

    public String put(DocumentImportDtos.PreviewSession session) {
        String sessionId = UUID.randomUUID().toString().replace("-", "");
        session.setSessionId(sessionId);
        defaultCache.put(buildKey(sessionId), session, SESSION_TTL.toMinutes(), TimeUnit.MINUTES);
        return sessionId;
    }

    /**
     * 为同一文档替换预览会话，返回被替换的旧会话供调用方清理对象存储工件。
     *
     * @param session 新预览会话
     * @return 旧会话；不存在时返回 {@code null}
     */
    public DocumentImportDtos.PreviewSession replaceForDocument(
        DocumentImportDtos.PreviewSession session) {
        String latestKey = buildLatestDocumentKey(
            session.getKnowledgeId(), session.getDocumentId());
        Object previousSessionId = defaultCache.get(latestKey);
        DocumentImportDtos.PreviewSession previous = null;
        if (previousSessionId instanceof String id) {
            Object cached = defaultCache.get(buildKey(id));
            if (cached instanceof DocumentImportDtos.PreviewSession oldSession) {
                previous = oldSession;
            }
        }
        String sessionId = put(session);
        defaultCache.put(
            latestKey, sessionId, SESSION_TTL.toMinutes(), TimeUnit.MINUTES);
        if (previousSessionId instanceof String id
            && !id.equals(sessionId)) {
            defaultCache.remove(buildKey(id));
        }
        return previous;
    }

    public DocumentImportDtos.PreviewSession getRequired(String sessionId) {
        Object cached = defaultCache.get(buildKey(sessionId));
        if (!(cached instanceof DocumentImportDtos.PreviewSession)) {
            throw new BusinessException("预览会话已失效，请重新生成预览");
        }
        return (DocumentImportDtos.PreviewSession) cached;
    }

    public void remove(String sessionId) {
        Object cached = defaultCache.get(buildKey(sessionId));
        defaultCache.remove(buildKey(sessionId));
        if (cached instanceof DocumentImportDtos.PreviewSession session) {
            String latestKey = buildLatestDocumentKey(
                session.getKnowledgeId(), session.getDocumentId());
            Object latestSessionId = defaultCache.get(latestKey);
            if (sessionId.equals(latestSessionId)) {
                defaultCache.remove(latestKey);
            }
        }
    }

    private String buildKey(String sessionId) {
        return DocumentImportKeys.CACHE_KEY_PREFIX + sessionId;
    }

    /**
     * 构造文档当前预览会话索引键。
     *
     * @param knowledgeId 知识库 ID
     * @param documentId 文档 ID
     * @return 缓存键
     */
    private String buildLatestDocumentKey(
        BigInteger knowledgeId,
        BigInteger documentId) {
        return DocumentImportKeys.CACHE_KEY_PREFIX
            + "latest:" + knowledgeId + ":" + documentId;
    }
}
