package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.DataService;
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 DataController {
    private final DataService dataService;

    @GetMapping("/join")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getJoinData(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(dataService.getJoinData(params)));
    }

    @GetMapping("/{tableName}")
    public ResponseEntity<Map<String, Object>> getTableData(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        params.put("table_name", tableName);
        try {
            Map<String, Object> svc = dataService.getTableData(params);
            Map<String, Object> response = new LinkedHashMap<>();
            response.put("success", true);
            response.put("data", svc.get("list"));
            response.put("total", svc.get("total"));
            response.put("page", svc.get("page"));
            response.put("size", svc.get("limit"));
            response.put("total_pages", svc.get("total_pages"));
            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);
        }
    }

    @GetMapping("/{tableName}/columns")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTableColumns(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName) {
        try {
            return ResponseEntity.ok(ApiResponse.success(dataService.getTableColumns(tableName)));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @GetMapping("/{tableName}/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getRecordDetail(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @PathVariable String id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("table_name", tableName);
        params.put("id", id);
        try {
            Map<String, Object> result = dataService.getRecordDetail(params);
            if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("레코드를 찾을 수 없습니다."));
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @PostMapping("/{tableName}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createRecord(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("table_name", tableName);
        try {
            return ResponseEntity.status(201).body(
                    ApiResponse.success(dataService.createRecord(body), "레코드가 생성되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @PutMapping("/{tableName}/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateRecord(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @PathVariable String id,
            @RequestBody Map<String, Object> body) {
        body.put("company_code", companyCode);
        body.put("table_name", tableName);
        body.put("id", id);
        try {
            Map<String, Object> result = dataService.updateRecord(body);
            if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("레코드를 찾을 수 없거나 수정 권한이 없습니다."));
            return ResponseEntity.ok(ApiResponse.success(result, "레코드가 수정되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }

    @DeleteMapping("/{tableName}/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteRecord(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tableName,
            @PathVariable String id) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("table_name", tableName);
        params.put("id", id);
        try {
            Map<String, Object> result = dataService.deleteRecord(params);
            if (result == null) return ResponseEntity.status(404).body(ApiResponse.error("레코드를 찾을 수 없습니다."));
            // Node.js는 data 없이 message만 반환
            return ResponseEntity.ok(ApiResponse.success(null, "레코드가 삭제되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        }
    }
}
