package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ExternalCallConfigService;
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-call-configs")
@RequiredArgsConstructor
@Slf4j
public class ExternalCallConfigController {

    private final ExternalCallConfigService externalCallConfigService;

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

    /**
     * GET /api/external-call-configs
     * ?call_type=&api_type=&is_active=Y&search=&page=1&limit=20
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getExternalCallConfigList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> queryParams) {
        queryParams.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(
            externalCallConfigService.getExternalCallConfigList(queryParams)));
    }

    // ── 버튼 제어용 목록 (리터럴 경로 - /{id} 보다 먼저 선언) ────────────────

    /**
     * GET /api/external-call-configs/for-button-control
     */
    @GetMapping("/for-button-control")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExternalCallConfigForButtonControl(
            @RequestAttribute("company_code") String companyCode) {
        return ResponseEntity.ok(ApiResponse.success(
            externalCallConfigService.getExternalCallConfigForButtonControl(companyCode)));
    }

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

    /**
     * GET /api/external-call-configs/:id
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getExternalCallConfigInfo(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("id", id);
        Map<String, Object> config = externalCallConfigService.getExternalCallConfigInfo(params);
        if (config == null) {
            return ResponseEntity.status(404)
                .body(ApiResponse.error("외부 호출 설정을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(config, "외부 호출 설정 조회 완료"));
    }

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

    /**
     * POST /api/external-call-configs
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertExternalCallConfig(
            @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);
        body.put("updated_by", userId);
        try {
            Map<String, Object> created = externalCallConfigService.insertExternalCallConfig(body);
            return ResponseEntity.status(201)
                .body(ApiResponse.success(created, "외부 호출 설정이 성공적으로 생성되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

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

    /**
     * PUT /api/external-call-configs/:id
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateExternalCallConfig(
            @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);
        body.put("id", id);
        try {
            Map<String, Object> updated = externalCallConfigService.updateExternalCallConfig(body);
            return ResponseEntity.ok(ApiResponse.success(updated, "외부 호출 설정이 성공적으로 수정되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        } catch (NoSuchElementException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ── 삭제 (논리 삭제) ────────────────────────────────────────────────────

    /**
     * DELETE /api/external-call-configs/:id
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteExternalCallConfig(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable int id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("company_code", companyCode);
        params.put("updated_by", userId);
        try {
            externalCallConfigService.deleteExternalCallConfig(params);
            return ResponseEntity.ok(ApiResponse.success(null, "외부 호출 설정이 성공적으로 삭제되었습니다."));
        } catch (NoSuchElementException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        }
    }

    // ── 설정 테스트 ────────────────────────────────────────────────────────

    /**
     * POST /api/external-call-configs/:id/test
     */
    @PostMapping("/{id}/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testExternalCallConfig(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable int id) {
        Map<String, Object> result = externalCallConfigService.testExternalCallConfig(id);
        String message = (String) result.get("message");
        return ResponseEntity.ok(ApiResponse.success(result, message));
    }

    // ── 설정 실행 ──────────────────────────────────────────────────────────

    /**
     * POST /api/external-call-configs/:id/execute
     */
    @PostMapping("/{id}/execute")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeExternalCallConfig(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @PathVariable int id,
            @RequestBody(required = false) Map<String, Object> body) {
        Map<String, Object> contextData = body != null ? new HashMap<>(body) : new HashMap<>();
        contextData.put("user_id", userId);
        contextData.put("company_code", companyCode);
        Map<String, Object> result = externalCallConfigService.executeExternalCallConfig(id, contextData);
        String message = (String) result.get("message");
        return ResponseEntity.ok(ApiResponse.success(result, message));
    }
}
