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.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;
    }

    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) {
        defaultCache.remove(buildKey(sessionId));
    }

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