package tech.easyflow.ai.easyagentsflow.repository;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheException;
import com.alicp.jetcache.CacheGetResult;
import com.alicp.jetcache.CacheResult;
import com.alicp.jetcache.CacheResultCode;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 工作流运行状态缓存仓储基类。
 */
public class BaseRepository {

    @Resource(name = "defaultCache")
    private Cache<String, Object> cache;

    /**
     * 保存工作流运行状态，缓存有效期为三天。
     *
     * @param key 缓存键
     * @param value 缓存值
     * @throws CacheException 缓存写入失败时抛出
     */
    protected void putCache(String key, Object value) {
        CacheResult result = cache.PUT(key, value, 3, TimeUnit.DAYS);
        if (!result.isSuccess()) {
            throw cacheOperationException("写入", key, result);
        }
    }

    /**
     * 读取并校验工作流运行状态缓存。
     *
     * @param key 缓存键
     * @param clazz 期望的缓存值类型
     * @param <T> 缓存值类型
     * @return 命中的缓存值；缓存不存在或已过期时返回 null
     * @throws CacheException 缓存读取失败时抛出
     * @throws ClassCastException 缓存值类型与期望类型不一致时抛出
     */
    protected <T> T getCache(String key, Class<T> clazz) {
        CacheGetResult<Object> result = cache.GET(key);
        CacheResultCode resultCode = result.getResultCode();
        if (resultCode == CacheResultCode.NOT_EXISTS || resultCode == CacheResultCode.EXPIRED) {
            return null;
        }
        if (!result.isSuccess()) {
            throw cacheOperationException("读取", key, result);
        }
        Object value = result.getValue();
        if (value == null) {
            return null;
        }
        return clazz.cast(value);
    }

    /**
     * 删除并校验工作流运行状态缓存。
     *
     * @param key 缓存键
     */
    protected void removeCache(String key) {
        CacheResult result = cache.REMOVE(key);
        CacheResultCode resultCode = result.getResultCode();
        if (resultCode == CacheResultCode.NOT_EXISTS || resultCode == CacheResultCode.EXPIRED) {
            return;
        }
        if (!result.isSuccess()) {
            throw cacheOperationException("删除", key, result);
        }
    }

    /**
     * 构建包含缓存操作上下文的异常。
     *
     * @param operation 操作名称
     * @param key 缓存键
     * @param result JetCache 操作结果
     * @return 缓存操作异常
     */
    private CacheException cacheOperationException(String operation, String key, CacheResult result) {
        return new CacheException(
            "工作流状态缓存" + operation + "失败，key=" + key
                + "，resultCode=" + result.getResultCode()
                + "，message=" + result.getMessage()
        );
    }
}
