package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ExternalCallService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/external-calls")
@RequiredArgsConstructor
@Slf4j
public class ExternalCallController {

    private final ExternalCallService service;

    // ── 외부 호출 테스트 ────────────────────────────────────────────────────────

    @SuppressWarnings("unchecked")
    @PostMapping("/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testExternalCall(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        Map<String, Object> settings = (Map<String, Object>) body.get("settings");
        if (settings == null) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("외부 호출 설정이 필요합니다."));
        }

        // 설정 검증
        Map<String, Object> validation = service.validateExternalCallSettings(settings);
        if (!Boolean.TRUE.equals(validation.get("valid"))) {
            Map<String, Object> errorData = new LinkedHashMap<>();
            errorData.put("errors", validation.get("errors"));
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("설정 검증 실패"));
        }

        // 테스트 요청 생성
        Map<String, Object> templateData = (Map<String, Object>) body.get("template_data");
        if (templateData == null) {
            templateData = Map.of(
                "record_count", 5,
                "table_name", "test_table",
                "timestamp", new Date().toString()
            );
        }

        Map<String, Object> request = new LinkedHashMap<>();
        request.put("diagram_id", 0);
        request.put("relationship_id", "test");
        request.put("settings", settings);
        request.put("template_data", templateData);

        Map<String, Object> result = service.executeExternalCall(request);
        boolean success = Boolean.TRUE.equals(result.get("success"));

        if (success) {
            return ResponseEntity.ok(ApiResponse.success(result, "외부 호출 테스트 성공"));
        }
        return ResponseEntity.ok(ApiResponse.success(result, "외부 호출 테스트 실패"));
    }

    // ── 외부 호출 실행 ──────────────────────────────────────────────────────────

    @SuppressWarnings("unchecked")
    @PostMapping("/execute")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeExternalCall(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        Object diagramId = body.get("diagram_id");
        String relationshipId = (String) body.get("relationship_id");
        Map<String, Object> settings = (Map<String, Object>) body.get("settings");

        if (diagramId == null || relationshipId == null || settings == null) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("필수 파라미터가 누락되었습니다. (diagramId, relationshipId, settings)"));
        }

        // 설정 검증
        Map<String, Object> validation = service.validateExternalCallSettings(settings);
        if (!Boolean.TRUE.equals(validation.get("valid"))) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("설정 검증 실패"));
        }

        Map<String, Object> result = service.executeExternalCall(body);
        boolean success = Boolean.TRUE.equals(result.get("success"));

        if (success) {
            return ResponseEntity.ok(ApiResponse.success(result, "외부 호출 실행 성공"));
        }
        return ResponseEntity.ok(ApiResponse.success(result, "외부 호출 실행 실패"));
    }

    // ── 지원 타입 목록 ──────────────────────────────────────────────────────────

    @GetMapping("/types")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getExternalCallTypeList(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> types = service.getExternalCallTypeList();
        return ResponseEntity.ok(ApiResponse.success(types, "지원되는 외부 호출 타입 목록"));
    }

    // ── 설정 검증 ──────────────────────────────────────────────────────────────

    @SuppressWarnings("unchecked")
    @PostMapping("/validate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> validateExternalCallSettings(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        Map<String, Object> settings = (Map<String, Object>) body.get("settings");
        if (settings == null) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("검증할 설정이 필요합니다."));
        }

        Map<String, Object> validation = service.validateExternalCallSettings(settings);
        return ResponseEntity.ok(ApiResponse.success(validation, "설정 검증 완료"));
    }
}
