package tech.easyflow.common.cache;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheManager;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.template.QuickConfig;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Function;

/**
 * EasyFlow 缓存基础配置。
 */
@Configuration
public class CacheConfig {

    @Autowired
    private CacheManager cacheManager;
    @Value("${jetcache.cacheType}")
    private String cacheType;

    private Cache<String, Object> defaultCache;

    /**
     * 根据平台配置初始化默认缓存。
     */
    @PostConstruct
    public void init() {
        CacheType type = CacheType.LOCAL;
        if ("remote".equals(cacheType)) {
            type = CacheType.REMOTE;
        }
        if ("both".equals(cacheType)) {
            type = CacheType.BOTH;
        }
        QuickConfig quickConfig = QuickConfig.newBuilder("")
                .cacheType(type)
                .build();
        defaultCache = cacheManager.getOrCreateCache(quickConfig);
    }

    /**
     * 获取平台默认缓存。
     *
     * @return 默认缓存实例
     */
    @Bean("defaultCache")
    public Cache<String, Object> getDefaultCache() {
        return defaultCache;
    }

    /**
     * 创建固定使用应用类加载器的 JetCache Java 解码器。
     *
     * @return JetCache 缓存值解码函数
     */
    @Bean("easyFlowJetCacheValueDecoder")
    public static Function<byte[], Object> easyFlowJetCacheValueDecoder() {
        return new ApplicationClassLoaderJavaValueDecoder();
    }
}
