package com.yaoyicloud.config;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class ReportPathManager {

    private static final String KEY_PREFIX = "reports:";
    private static final long DEF_REPORT_TTL = 1 * 60 * 60 * 1000;

    private final RedisTemplate<String, String> redisTemplate;
    private final ListOperations<String, String> listOps;

    public ReportPathManager(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.listOps = redisTemplate.opsForList();
    }

    /**
     * 生成Redis键：session:{sessionId}:reports
     */
    private String getReportKey(String sessionId) {
        return KEY_PREFIX + sessionId;
    }

    /**
     * 为列表键设置过期时间（若已存在则刷新过期时间）
     */
    private void setExpire(String key) {
        redisTemplate.expire(key, DEF_REPORT_TTL, TimeUnit.MILLISECONDS);
    }

    /**
     * 添加单个报告路径（按插入顺序有序）
     */
    public void addReportPath(String sessionId, String reportPath) {
        String key = getReportKey(sessionId);
        listOps.rightPush(key, reportPath);
        setExpire(key);
    }

    /**
     * 批量添加报告路径（按集合迭代顺序插入，保证整体有序性）
     */
    public void addReportPaths(String sessionId, Collection<String> reportPaths) {
        String key = getReportKey(sessionId);
        listOps.rightPushAll(key, reportPaths.toArray(new String[0]));
        setExpire(key);
    }

    /**
     * 获取指定sessionId下的所有报告路径（按插入顺序返回）
     */
    public List<String> getReportPaths(String sessionId) {
        String key = getReportKey(sessionId);
        return listOps.range(key, 0, -1);
    }

    /**
     * 检查sessionId是否存在
     */
    public boolean hasSession(String sessionId) {
        String key = getReportKey(sessionId);
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取所有报告路径的总数（注意：需遍历所有key，可能影响性能）
     */
    public int getTotalReportCount() {
        Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
        if (keys == null || keys.isEmpty()) {
            return 0;
        }
        return keys.stream()
            .mapToInt(key -> listOps.size(key).intValue())
            .sum();
    }

    /**
     * 移除指定sessionId及其所有报告路径
     */
    public List<String> removeSession(String sessionId) {
        String key = getReportKey(sessionId);
        List<String> result = listOps.range(key, 0, -1);
        redisTemplate.delete(key);
        return result != null ? result : Collections.emptyList();
    }

    /**
     * 清空所有数据（注意：会删除所有以session:开头的键）
     */
    public void clear() {
        Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
