package com.eactive.eai.manage.inflow;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 어댑터/인터페이스 유량제어 메트릭 API.
 *
 * DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
 *
 * GET  /manage/inflow/adapter/metric                      → 전체 어댑터 메트릭
 * GET  /manage/inflow/adapter/{adapterId}/metric          → 특정 어댑터 메트릭
 * POST /manage/inflow/adapter/metric/reset                → 전체 어댑터 메트릭 초기화
 * POST /manage/inflow/adapter/{adapterId}/metric/reset    → 특정 어댑터 메트릭 초기화
 *
 * GET  /manage/inflow/interface/metric                    → 전체 인터페이스 메트릭
 * GET  /manage/inflow/interface/{interfaceId}/metric      → 특정 인터페이스 메트릭
 * POST /manage/inflow/interface/metric/reset              → 전체 인터페이스 메트릭 초기화
 * POST /manage/inflow/interface/{interfaceId}/metric/reset → 특정 인터페이스 메트릭 초기화
 */
@RestController
@RequestMapping("/manage/inflow")
public class InflowTargetMetricController {

    @Autowired
    private InflowTargetMetricService metricService;

    // =========================================================================
    // 어댑터
    // =========================================================================

    @GetMapping("/adapter/metric")
    public ResponseEntity<?> getAllAdapterMetrics() {
        List<TargetMetricDTO> list = metricService.getAllAdapterMetrics();
        return okList(list);
    }

    @GetMapping("/adapter/{adapterId}/metric")
    public ResponseEntity<?> getAdapterMetric(@PathVariable String adapterId) {
        TargetMetricDTO dto = metricService.getAdapterMetric(adapterId);
        return okSingle(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
    }

    @PostMapping("/adapter/metric/reset")
    public ResponseEntity<?> resetAllAdapterMetrics() {
        metricService.resetAllAdapterMetrics();
        return okReset("전체 어댑터 메트릭 초기화 완료");
    }

    @PostMapping("/adapter/{adapterId}/metric/reset")
    public ResponseEntity<?> resetAdapterMetric(@PathVariable String adapterId) {
        boolean ok = metricService.resetAdapterMetric(adapterId);
        return okResetSingle(ok, adapterId, "어댑터");
    }

    // =========================================================================
    // 인터페이스
    // =========================================================================

    @GetMapping("/interface/metric")
    public ResponseEntity<?> getAllInterfaceMetrics() {
        List<TargetMetricDTO> list = metricService.getAllInterfaceMetrics();
        return okList(list);
    }

    @GetMapping("/interface/{interfaceId}/metric")
    public ResponseEntity<?> getInterfaceMetric(@PathVariable String interfaceId) {
        TargetMetricDTO dto = metricService.getInterfaceMetric(interfaceId);
        return okSingle(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
    }

    @PostMapping("/interface/metric/reset")
    public ResponseEntity<?> resetAllInterfaceMetrics() {
        metricService.resetAllInterfaceMetrics();
        return okReset("전체 인터페이스 메트릭 초기화 완료");
    }

    @PostMapping("/interface/{interfaceId}/metric/reset")
    public ResponseEntity<?> resetInterfaceMetric(@PathVariable String interfaceId) {
        boolean ok = metricService.resetInterfaceMetric(interfaceId);
        return okResetSingle(ok, interfaceId, "인터페이스");
    }

    // =========================================================================
    // Helpers
    // =========================================================================

    private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", list);
        result.put("count", list.size());
        return ResponseEntity.ok(result);
    }

    private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
        if (dto == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", notFoundMsg);
            return ResponseEntity.ok(error);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", dto);
        return ResponseEntity.ok(result);
    }

    private ResponseEntity<?> okReset(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", message);
        return ResponseEntity.ok(result);
    }

    private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", ok);
        result.put("message", ok
            ? "초기화 완료: " + targetId
            : targetLabel + "를 찾을 수 없습니다: " + targetId);
        return ResponseEntity.ok(result);
    }
}
