package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.DataAdvancedService;
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/data")
@RequiredArgsConstructor
@Slf4j
public class DataAdvancedController {

    private final DataAdvancedService dataAdvancedService;

    @PostMapping("/upsert-grouped")
    public ResponseEntity<Map<String, Object>> upsertGrouped(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        try {
            Map<String, Object> result = dataAdvancedService.upsertGrouped(body);
            Map<String, Object> response = new LinkedHashMap<>();
            response.put("success", true);
            response.put("message", "데이터가 저장되었습니다.");
            response.put("inserted", result.getOrDefault("inserted", 0));
            response.put("updated", result.getOrDefault("updated", 0));
            response.put("deleted", result.getOrDefault("deleted", 0));
            response.put("saved_ids", result.getOrDefault("saved_ids", Collections.emptyList()));
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> err = new LinkedHashMap<>();
            err.put("success", false);
            err.put("message", e.getMessage());
            return ResponseEntity.status(400).body(err);
        }
    }

    @PostMapping("/{tableName}/delete")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteByCondition(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @RequestBody Map<String, Object> body) {
        // Node.js는 복합키를 body에 직접 전송 (e.g. {user_id: 'x', dept_code: 'y'})
        // DataService.deleteByCompositeKey는 params.get("keys")를 기대하므로 래핑
        Map<String, Object> keys = new LinkedHashMap<>(body);
        keys.remove("table_name");
        keys.remove("company_code");

        Map<String, Object> params = new LinkedHashMap<>();
        params.put("company_code", companyCode);
        params.put("table_name", tableName);
        params.put("keys", keys);
        try {
            return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.deleteByCondition(params)));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @PostMapping("/{tableName}/delete-group")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteGroup(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @RequestBody Map<String, Object> body) {
        // Node.js는 필터 조건을 body에 직접 전송
        // DataService.deleteGroupRecords는 params.get("filters")를 기대하므로 래핑
        Map<String, Object> filters = new LinkedHashMap<>(body);
        filters.remove("table_name");
        filters.remove("company_code");

        Map<String, Object> params = new LinkedHashMap<>();
        params.put("company_code", companyCode);
        params.put("table_name", tableName);
        params.put("filters", filters);
        try {
            return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.deleteGroup(params)));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/multi-table/auto-detect")
    public ResponseEntity<ApiResponse<Map<String, Object>>> autoDetectMultiTable(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.autoDetectMultiTable(params)));
    }

    @PostMapping("/multi-table/upload")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadMultiTable(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.uploadMultiTable(body)));
    }

    @GetMapping("/master-detail/relation/{screenId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMasterDetailRelation(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String screenId) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("screen_id", screenId);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.getMasterDetailRelation(params)));
    }

    @PostMapping("/master-detail/download")
    public ResponseEntity<ApiResponse<Map<String, Object>>> downloadMasterDetail(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.downloadMasterDetail(body)));
    }

    @PostMapping("/master-detail/upload")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadMasterDetail(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.uploadMasterDetail(body)));
    }

    @PostMapping("/master-detail/upload-simple")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadMasterDetailSimple(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataAdvancedService.uploadMasterDetailSimple(body)));
    }
}
