package com.erp.controller;

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

import java.util.Map;

/**
 * 데이터플로우 실행 컨트롤러
 *
 * POST /api/dataflow/execute-data-action
 *   body: { tableName, data, actionType, connection? }
 */
@RestController
@RequestMapping("/api/dataflow")
@RequiredArgsConstructor
@Slf4j
public class DataflowExecutionController {

    private final DataflowExecutionService service;

    @PostMapping("/execute-data-action")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeDataAction(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        try {
            body.put("company_code", companyCode);

            log.info("데이터 액션 실행 요청: action={}, table={}",
                    body.get("action_type"), body.get("table_name"));

            Map<String, Object> result = service.executeDataAction(body);
            return ResponseEntity.ok(
                    ApiResponse.success(result, "데이터 액션 실행 완료: " + body.get("action_type")));

        } catch (IllegalArgumentException e) {
            log.warn("데이터 액션 파라미터 오류: {}", e.getMessage());
            return ResponseEntity.status(400)
                    .body(ApiResponse.error(e.getMessage()));
        } catch (IllegalStateException e) {
            // 중복 값 등 비즈니스 규칙 위반
            log.warn("데이터 액션 비즈니스 오류: {}", e.getMessage());
            return ResponseEntity.status(409)
                    .body(ApiResponse.error(e.getMessage()));
        } catch (UnsupportedOperationException e) {
            log.warn("지원하지 않는 액션: {}", e.getMessage());
            return ResponseEntity.status(400)
                    .body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("데이터 액션 실행 실패: {}", e.getMessage(), e);
            return ResponseEntity.status(500)
                    .body(ApiResponse.error("데이터 액션 실행 실패: " + e.getMessage()));
        }
    }
}
