import com.red.circle.OtherServiceApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@SpringBootTest(classes = OtherServiceApplication.class)
@RunWith(SpringRunner.class)
@Slf4j
public class ResetVipLevelTest {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String VIP_LEVEL_KEY_PATTERN = "GAME:VIP:LEVEL:*";
    private static final long EXPIRE_DAYS = 7;

    /**
     * 批量将所有用户 VIP 等级缓存重置为 0，TTL 设置为 7 天
     */
    @Test
    public void resetAllVipLevelToZero() {
        ScanOptions options = ScanOptions.scanOptions()
                .match(VIP_LEVEL_KEY_PATTERN)
                .count(500)
                .build();

        int[] count = {0};

        redisTemplate.execute((RedisCallback<Object>) connection -> {
            Cursor<byte[]> cursor = connection.scan(options);
            while (cursor.hasNext()) {
                String key = new String(cursor.next());
                redisTemplate.opsForValue().set(key, 0, EXPIRE_DAYS, TimeUnit.DAYS);
                count[0]++;
                if (count[0] % 100 == 0) {
                    log.info("已处理: {} 条", count[0]);
                }
            }
            cursor.close();
            return null;
        });

        log.info("完成，共重置 {} 个用户 VIP 缓存 -> 0，TTL={}天", count[0], EXPIRE_DAYS);

    }
}
