package com.haobang.controller;

import com.haobang.interlocking.InterlockingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 探针联动控制器
 * 提供手动触发封禁的REST API
 */
@RestController
@RequestMapping("/interlocking")
public class InterlockingController {

    @Autowired
    private InterlockingService interlockingService;

    /**
     * 手动封禁单个IP
     * POST /interlocking/block
     * 
     * @param request 封禁请求参数
     * @return 执行结果
     */
    @PostMapping("/block")
    public ResponseEntity<Map<String, Object>> blockIp(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String ip = (String) request.get("ip");
            String cmdType = (String) request.getOrDefault("cmdType", "add_blacklist");
            Integer age = request.containsKey("age") ? ((Number) request.get("age")).intValue() : -1;
            String reason = (String) request.getOrDefault("reason", "manual_block");

            if (ip == null || ip.isEmpty()) {
                result.put("code", 400);
                result.put("message", "IP地址不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            Map<String, Object> response = interlockingService.manualBlock(ip, cmdType, age, reason);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", response);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "封禁失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量封禁IP
     * POST /interlocking/block/batch
     * 
     * @param request 批量封禁请求参数
     * @return 执行结果
     */
    @PostMapping("/block/batch")
    public ResponseEntity<Map<String, Object>> batchBlockIp(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            @SuppressWarnings("unchecked")
            List<String> ips = (List<String>) request.get("ips");
            String cmdType = (String) request.getOrDefault("cmdType", "add_blacklist");
            Integer age = request.containsKey("age") ? ((Number) request.get("age")).intValue() : -1;
            String reason = (String) request.getOrDefault("reason", "manual_batch_block");

            if (ips == null || ips.isEmpty()) {
                result.put("code", 400);
                result.put("message", "IP地址列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            Map<String, Object> response = interlockingService.batchManualBlock(ips, cmdType, age, reason);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", response);
            result.put("total", ips.size());
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量封禁失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 从黑名单删除IP
     * DELETE /interlocking/blacklist/{ip}
     */
    @DeleteMapping("/blacklist/{ip}")
    public ResponseEntity<Map<String, Object>> removeFromBlacklist(@PathVariable String ip) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> response = interlockingService.manualBlock(ip, "del_blacklist", -1, "");
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", response);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除黑名单失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量从黑名单删除IP
     * DELETE /interlocking/blacklist
     */
    @DeleteMapping("/blacklist")
    public ResponseEntity<Map<String, Object>> batchRemoveFromBlacklist(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            @SuppressWarnings("unchecked")
            List<String> ips = (List<String>) request.get("ips");
            
            if (ips == null || ips.isEmpty()) {
                result.put("code", 400);
                result.put("message", "IP地址列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            Map<String, Object> response = interlockingService.batchManualBlock(ips, "del_blacklist", -1, "");
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", response);
            result.put("total", ips.size());
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量删除黑名单失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取联动服务状态
     * GET /interlocking/status
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            result.put("code", 200);
            result.put("message", "success");
            
            Map<String, Object> status = new HashMap<>();
            status.put("enabled", interlockingService.isInterlockingEnabled());
            status.put("probeId", interlockingService.getProbeId());
            result.put("data", status);
            
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 健康检查
     * GET /interlocking/health
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "OK");
        result.put("service", "interlocking-client");
        result.put("probeId", interlockingService.getProbeId());
        result.put("enabled", interlockingService.isInterlockingEnabled());
        return ResponseEntity.ok(result);
    }
}
