package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ExcelMappingService;
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/excel-mapping")
@RequiredArgsConstructor
@Slf4j
public class ExcelMappingController {

    private final ExcelMappingService excelMappingService;

    @PostMapping("/find")
    public ResponseEntity<ApiResponse<Map<String, Object>>> findMappingByColumns(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("excel_columns") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("tableName과 excelColumns는 필수입니다."));
        }
        body.put("company_code", companyCode);
        Map<String, Object> result = excelMappingService.findMappingByColumns(body);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PostMapping("/save")
    public ResponseEntity<ApiResponse<Map<String, Object>>> saveMappingTemplate(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        if (body.get("table_name") == null || body.get("excel_columns") == null || body.get("column_mappings") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("tableName, excelColumns, columnMappings는 필수입니다."));
        }
        body.put("company_code", companyCode);
        Map<String, Object> result = excelMappingService.saveMappingTemplate(body);
        return ResponseEntity.ok(ApiResponse.success(result, "매핑 템플릿이 저장되었습니다."));
    }

    @GetMapping("/list/{tableName}")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMappingTemplates(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName) {
        Map<String, Object> params = new HashMap<>();
        params.put("table_name", tableName);
        params.put("company_code", companyCode);
        List<Map<String, Object>> result = excelMappingService.getMappingTemplates(params);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteMappingTemplate(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("company_code", companyCode);
        boolean deleted = excelMappingService.deleteMappingTemplate(params);
        if (!deleted) {
            return ResponseEntity.status(404).body(ApiResponse.error("매핑 템플릿을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "매핑 템플릿이 삭제되었습니다."));
    }
}
