package com.zhentao.controller;

import com.zhentao.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis健康检查接口，用于验证连接、配置与基本读写能力。
 */
@RestController
@RequestMapping("/api/login/redis")
@CrossOrigin
public class RedisHealthController {

    @Autowired(required = false)
    private StringRedisTemplate stringRedisTemplate;

    @Value("${spring.redis.host:}")
    private String host;

    @Value("${spring.redis.port:0}")
    private int port;

    @Value("${spring.redis.database:0}")
    private int database;

    @Value("${spring.redis.password:}")
    private String password;

    @Value("${spring.redis.timeout:2000ms}")
    private String timeout;

    @Value("${redis.enabled:true}")
    private boolean redisEnabled;

    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        Map<String, Object> info = new HashMap<>();
        info.put("host", host);
        info.put("port", port);
        info.put("database", database);
        info.put("timeout", timeout);
        info.put("hasPassword", password != null && !password.isEmpty());

        String ping = null;
        String error = null;
        boolean setGetOk = false;
        info.put("enabled", redisEnabled);
        if (!redisEnabled) {
            info.put("status", "DISABLED");
            return Result.success(info);
        }
        try {
            if (stringRedisTemplate == null) {
                throw new IllegalStateException("StringRedisTemplate not injected");
            }
            RedisConnectionFactory cf = stringRedisTemplate.getConnectionFactory();
            if (cf != null) {
                RedisConnection conn = cf.getConnection();
                try {
                    ping = conn.ping();
                } finally {
                    try { conn.close(); } catch (Exception ignore) {}
                }
            }

            String key = "health:probe";
            String val = "ok";
            stringRedisTemplate.opsForValue().set(key, val, Duration.ofSeconds(5));
            String got = stringRedisTemplate.opsForValue().get(key);
            setGetOk = val.equals(got);
        } catch (Exception e) {
            error = e.getClass().getSimpleName() + ": " + e.getMessage();
        }

        info.put("ping", ping);
        info.put("setGetOk", setGetOk);
        info.put("error", error);
        info.put("status", ("PONG".equalsIgnoreCase(ping) && setGetOk && error == null) ? "UP" : "DOWN");
        return Result.success(info);
    }
}