package org.dromara.job.cycle;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.project.constant.BusProjectConstant;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class IncSyncDeleteProjectCache {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 每天凌晨 12 点执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void run() {
        log.info("执行定时任务：清理项目缓存");
        // 构建扫描选项
        ScanOptions scanOptions = ScanOptions.scanOptions()
            .match(BusProjectConstant.PROJECT_CACHE_REDIS_KEY_PREFIX + "*")
            .count(1000) // 每次 scan 的数量
            .build();
        Set<String> keysToDelete = new HashSet<>();
        Cursor<byte[]> cursor = stringRedisTemplate.getConnectionFactory()
            .getConnection()
            .scan(scanOptions);
        while (cursor.hasNext()) {
            keysToDelete.add(new String(cursor.next()));
        }
        // 批量删除
        if (!keysToDelete.isEmpty()) {
            stringRedisTemplate.delete(keysToDelete);
        }
    }
}
