package com.erp.controller;

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

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/entity-reference")
@RequiredArgsConstructor
@Slf4j
public class EntityReferenceController {

    private final EntityReferenceService entityReferenceService;

    /**
     * GET /api/entity-reference/code/:codeInfo
     * 공통 코드 데이터 조회
     *
     * NOTE: Spring MVC는 리터럴 경로 세그먼트("code")를 변수 경로({tableName})보다 우선하므로
     *       /code/{codeInfo} 가 /{tableName}/{columnName} 보다 먼저 매핑됨.
     */
    @GetMapping("/code/{codeInfo}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCodeData(
            @PathVariable String codeInfo,
            @RequestParam(required = false, defaultValue = "100") Integer limit,
            @RequestParam(required = false) String search,
            @RequestAttribute("company_code") String companyCode) {

        Map<String, Object> params = new HashMap<>();
        params.put("code_info", codeInfo);
        params.put("company_code",  companyCode);
        params.put("limit",        limit);
        if (search != null) params.put("search", search);

        try {
            return ResponseEntity.ok(ApiResponse.success(entityReferenceService.getCodeData(params)));
        } catch (Exception e) {
            log.error("공통 코드 데이터 조회 실패: codeInfo={}", codeInfo, e);
            return ResponseEntity.status(500).body(ApiResponse.error("공통 코드 데이터 조회 중 오류가 발생했습니다."));
        }
    }

    /**
     * GET /api/entity-reference/:tableName/:columnName
     * 엔티티 참조 데이터 조회
     */
    @GetMapping("/{tableName}/{columnName}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getEntityReferenceData(
            @PathVariable String tableName,
            @PathVariable String columnName,
            @RequestParam(required = false, defaultValue = "100") Integer limit,
            @RequestParam(required = false) String search,
            @RequestAttribute("company_code") String companyCode) {

        Map<String, Object> params = new HashMap<>();
        params.put("table_name",   tableName);
        params.put("column_name",  columnName);
        params.put("company_code", companyCode);
        params.put("limit",       limit);
        if (search != null) params.put("search", search);

        try {
            return ResponseEntity.ok(ApiResponse.success(entityReferenceService.getEntityReferenceData(params)));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        } catch (IllegalStateException e) {
            return ResponseEntity.status(400).body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("엔티티 참조 데이터 조회 실패: {}.{}", tableName, columnName, e);
            return ResponseEntity.status(500).body(ApiResponse.error("엔티티 참조 데이터 조회 중 오류가 발생했습니다."));
        }
    }
}
