package tech.easyflow.ai.easyagentsflow.repository;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import tech.easyflow.ai.easyagentsflow.support.PublishedWorkflowDefinitionIds;
import tech.easyflow.common.constant.CacheKey;

import java.time.Duration;
import java.util.UUID;

/**
 * 基于 Redis 的工作流定义缓存版本令牌仓储。
 */
@Component
public class RedisWorkflowDefinitionVersionStore implements WorkflowDefinitionVersionStore {

    private static final Duration TOKEN_TTL = Duration.ofDays(7);

    private final StringRedisTemplate redisTemplate;

    /**
     * 创建版本令牌仓储。
     *
     * @param redisTemplate Redis 字符串模板
     */
    public RedisWorkflowDefinitionVersionStore(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String currentToken(String definitionId) {
        String key = versionKey(definitionId);
        String current = redisTemplate.opsForValue().get(key);
        if (current != null) {
            return current;
        }
        String candidate = UUID.randomUUID().toString();
        Boolean created = redisTemplate.opsForValue().setIfAbsent(key, candidate, TOKEN_TTL);
        if (Boolean.TRUE.equals(created)) {
            return candidate;
        }
        current = redisTemplate.opsForValue().get(key);
        if (current == null) {
            throw new IllegalStateException("Workflow definition version token is unavailable: " + definitionId);
        }
        return current;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void invalidateWorkflow(String workflowId) {
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(versionKey(workflowId), token, TOKEN_TTL);
        redisTemplate.opsForValue().set(
                versionKey(PublishedWorkflowDefinitionIds.published(workflowId)),
                token,
                TOKEN_TTL);
    }

    /**
     * 构建版本令牌 Redis 键。
     *
     * @param definitionId 定义 ID
     * @return Redis 键
     */
    private String versionKey(String definitionId) {
        return CacheKey.WORKFLOW_DEFINITION_VERSION_KEY + definitionId;
    }
}
