package com.controllers;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/cache")
public class CacheController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    private CacheManager cacheManager;

    /**
     * 获取指定key的缓存值
     */
    @GetMapping("/key/{key}")
    public ResponseEntity<Map<String, Object>> getCacheValue(@PathVariable String key) {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            Map<String, Object> result = new HashMap<>();
            result.put("key", key);
            result.put("value", value);
            result.put("exists", value != null);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "获取缓存失败");
            errorMap.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 清除指定key的缓存
     */
    @DeleteMapping("/key/{key}")
    public ResponseEntity<Map<String, Object>> deleteCache(@PathVariable String key) {
        try {
            Boolean deleted = redisTemplate.delete(key);
            Map<String, Object> result = new HashMap<>();
            result.put("key", key);
            result.put("deleted", deleted);
            result.put("message", deleted ? "缓存删除成功" : "缓存不存在");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "删除缓存失败");
            errorMap.put("message", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(errorMap);
        }
    }


    /**
     * 清除所有缓存（清空整个Redis数据库）
     * 警告：这是一个危险操作，会清空所有数据
     */
    @DeleteMapping("/all")
    public ResponseEntity<Map<String, Object>> clearAllCache() {
        try {
            // 获取当前数据库的所有key
            Set<String> keys = redisTemplate.keys("*");
            Long deletedCount = 0L;

            if (keys != null && !keys.isEmpty()) {
                deletedCount = redisTemplate.delete(keys);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("operation", "clearAll");
            result.put("deletedCount", deletedCount);
            result.put("message", "所有缓存已清除");
            result.put("warning", "此操作会清空整个Redis数据库，请谨慎使用！");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "清除所有缓存失败");
            errorMap.put("message", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(errorMap);
        }
    }

    /**
     * 清除指定缓存名称的所有缓存（通过CacheManager）
     * 例如：deviceCache、userCache等
     */
    @DeleteMapping("/name/{cacheName}")
    public ResponseEntity<Map<String, Object>> clearCacheByName(@PathVariable String cacheName) {
        try {
            if (cacheManager == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "CacheManager未配置");
                errorMap.put("message", "无法通过CacheManager清除缓存");
                return ResponseEntity.badRequest()
                        .body(errorMap);
            }

            Cache cache = cacheManager.getCache(cacheName);
            if (cache == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("cacheName", cacheName);
                errorMap.put("message", "缓存不存在");
                errorMap.put("availableCaches",  cacheManager.getCacheNames());
                return ResponseEntity.ok(errorMap);
            }

            cache.clear();

            Map<String, Object> result = new HashMap<>();
            result.put("cacheName", cacheName);
            result.put("operation", "clear");
            result.put("message", "缓存区域已清空");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "清除缓存失败");
            errorMap.put("message", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(errorMap);
        }
    }

    /**
     * 获取所有缓存名称（通过CacheManager）
     */
    @GetMapping("/names")
    public ResponseEntity<Map<String, Object>> getAllCacheNames() {
        try {
            if (cacheManager == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("caches",  Collections.emptyList());
                errorMap.put("message","CacheManager未配置");
                return ResponseEntity.ok(errorMap);
            }

            Collection<String> cacheNames = cacheManager.getCacheNames();
            Map<String, Object> result = new HashMap<>();
            result.put("count", cacheNames.size());
            result.put("caches", cacheNames);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "获取缓存名称失败");
            errorMap.put("message",e.getMessage());
            return ResponseEntity.badRequest()
                    .body(errorMap);
        }
    }

    /**
     * 获取所有Redis key（按模式搜索）
     */
    @GetMapping("/redis-keys")
    public ResponseEntity<Map<String, Object>> getRedisKeys(@RequestParam(required = false, defaultValue = "*") String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern);
            if (keys == null) {
                keys = Collections.emptySet();
            }

            // 获取key对应的value类型（可选）
            List<Map<String, Object>> keyDetails = keys.stream()
                    .limit(100) // 限制返回数量，避免数据量太大
                    .map(key -> {
                        Map<String, Object> detail = new HashMap<>();
                        detail.put("key", key);
                        try {
                            // 获取key的类型
                            String type = redisTemplate.type(key).name();
                            detail.put("type", type);

                            // 获取TTL（过期时间）
                            Long ttl = redisTemplate.getExpire(key);
                            detail.put("ttl", ttl);

                            // 获取key的大小（估计值）
                            if ("STRING".equals(type)) {
                                Object value = redisTemplate.opsForValue().get(key);
                                detail.put("size", value != null ? value.toString().length() : 0);
                            }
                        } catch (Exception e) {
                            detail.put("error", e.getMessage());
                        }
                        return detail;
                    })
                    .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("pattern", pattern);
            result.put("totalKeys", keys.size());
            result.put("returnedKeys", keyDetails.size());
            result.put("keys", keyDetails);
            result.put("message", keys.size() > 100 ? "只显示前100个key" : "所有key已列出");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "获取Redis keys失败");
            errorMap.put("message",e.getMessage());
            return ResponseEntity.badRequest()
                    .body(errorMap);
        }
    }

}