package com.erp.controller;

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

import java.util.Map;

@RestController
@RequestMapping("/api/pop-action")
@RequiredArgsConstructor
@Slf4j
public class PopActionController {

    private final PopActionService popActionService;

    /**
     * POST /api/pop-action/execute-action
     * Node.js popActionRoutes.ts POST /execute-action 대응
     */
    @PostMapping("/execute-action")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeAction(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        try {
            Map<String, Object> result = popActionService.executeAction(body, companyCode, userId);
            String message = result.containsKey("message") ? result.get("message").toString()
                    : result.get("processed_count") + "건 처리 완료";
            return ResponseEntity.ok(ApiResponse.success(result, message));
        } catch (PopActionService.PreConditionFailException e) {
            return ResponseEntity.status(409).body(ApiResponse.error(e.getMessage()));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }
}
