package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ExternalRestApiConnectionService;
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-rest-api-connections")
@RequiredArgsConstructor
@Slf4j
public class ExternalRestApiConnectionController {

    private final ExternalRestApiConnectionService service;

    // ── 목록 조회 ──────────────────────────────────────────────────────────────

    @GetMapping
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getConnections(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> queryParams) {
        queryParams.put("company_code", companyCode);
        List<Map<String, Object>> list = service.getExternalRestApiConnectionList(queryParams);
        return ResponseEntity.ok(
            ApiResponse.success(list, list.size() + "개의 REST API 연결을 조회했습니다."));
    }

    // ── 단건 조회 ──────────────────────────────────────────────────────────────

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getConnectionById(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("company_code", companyCode);
        Map<String, Object> conn = service.getExternalRestApiConnectionInfo(params);
        if (conn == null) {
            return ResponseEntity.status(404)
                .body(ApiResponse.error("해당 REST API 연결을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(conn, "REST API 연결을 조회했습니다."));
    }

    // ── 생성 ───────────────────────────────────────────────────────────────────

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createConnection(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("created_by", userId);
        try {
            Map<String, Object> created = service.insertExternalRestApiConnection(body);
            return ResponseEntity.status(201)
                .body(ApiResponse.success(created, "REST API 연결이 생성되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    // ── 수정 ───────────────────────────────────────────────────────────────────

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateConnection(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable int id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("updated_by", userId);
        Map<String, Object> updated = service.updateExternalRestApiConnection(id, body);
        if (updated == null) {
            return ResponseEntity.status(404)
                .body(ApiResponse.error("해당 REST API 연결을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(updated, "REST API 연결이 수정되었습니다."));
    }

    // ── 삭제 ───────────────────────────────────────────────────────────────────

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        boolean deleted = service.deleteExternalRestApiConnection(id, params);
        if (!deleted) {
            return ResponseEntity.status(404)
                .body(ApiResponse.error("해당 REST API 연결을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "REST API 연결이 삭제되었습니다."));
    }

    // ── 연결 테스트 (요청 데이터 기반) ──────────────────────────────────────────

    @PostMapping("/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testConnection(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        Map<String, Object> result = service.testConnection(body, companyCode);
        boolean success = Boolean.TRUE.equals(result.get("success"));
        return ResponseEntity.ok(ApiResponse.success(result,
            success ? "연결 테스트 성공" : "연결 테스트 실패"));
    }

    // ── 연결 테스트 (ID 기반) ───────────────────────────────────────────────────

    @PostMapping("/{id}/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testConnectionById(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id,
            @RequestBody(required = false) Map<String, Object> body) {
        String endpoint = body != null ? (String) body.get("endpoint") : null;
        Map<String, Object> result = service.testConnectionById(id, endpoint);
        boolean success = Boolean.TRUE.equals(result.get("success"));
        return ResponseEntity.ok(ApiResponse.success(result,
            success ? "연결 테스트 성공" : "연결 테스트 실패"));
    }

    // ── 데이터 조회 (프록시) ────────────────────────────────────────────────────

    @PostMapping("/{id}/fetch")
    public ResponseEntity<ApiResponse<Map<String, Object>>> fetchData(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id,
            @RequestBody(required = false) Map<String, Object> body) {
        Map<String, Object> params = body != null ? new HashMap<>(body) : new HashMap<>();
        params.put("company_code", companyCode);
        String endpoint = (String) params.get("endpoint");
        String jsonPath = (String) params.get("json_path");
        Map<String, Object> result = service.fetchData(id, endpoint, jsonPath, params);
        boolean success = Boolean.TRUE.equals(result.get("success"));
        if (!success) {
            return ResponseEntity.badRequest().body(ApiResponse.error(
                (String) result.getOrDefault("message", "데이터 조회 실패")));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }
}
