package org.jk.rag.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.jk.common.core.utils.SpringUtils;
import org.jk.system.domain.SysTenant;
import org.jk.system.domain.vo.SysTenantVo;
import org.jk.system.mapper.SysTenantMapper;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class ConfigSyncService {
    private final SysTenantMapper tenantMapper;
    private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);

    private static final String CONFIG_KEY = "company:concurrent:config";
    private static final int DEFAULT_MAX_CONCURRENT = 5;

    @PostConstruct
    public void initConfig() {
        syncConfigToRedis();
    }

    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void syncConfigToRedis() {
        List<SysTenant> configList = tenantMapper.selectList(null);
        // 使用 RMapCache 替代 RMap，支持 Field 过期
        RMapCache<String, Integer> configMap = CLIENT.getMapCache(CONFIG_KEY);

        for (SysTenant tenant : configList) {
            // 存入数据时可直接指定 Field 过期时间（可选）
            configMap.put(tenant.getTenantId(), tenant.getMaxConcurrent(), 1, TimeUnit.DAYS);
        }
    }

    public Integer getMaxConcurrent(String tenantId) {
        Integer maxConcurrent = null;
        try {
            SysTenantVo tenantVo = tenantMapper.selectVoOne(
                new LambdaQueryWrapper<SysTenant>().eq(SysTenant::getTenantId, tenantId)
            );
            if (tenantVo != null && "0".equals(tenantVo.getStatus())) {
                maxConcurrent = tenantVo.getMaxConcurrent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 最终兜底：返回默认值
        return (maxConcurrent != null && maxConcurrent > 0) ? maxConcurrent : 5;
    }
}
