package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.MetaService;
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.List;
import java.util.Map;

@RestController
@RequestMapping("/api/meta")
@RequiredArgsConstructor
@Slf4j
public class MetaController {

    private final MetaService metaService;

    /**
     * GET /api/meta/tables — 접근 가능한 테이블 목록
     */
    @GetMapping("/tables")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMetaTableList(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(metaService.getMetaTableList(params)));
    }

    /**
     * GET /api/meta/tables/{tableName}/fields — 특정 테이블의 FieldConfig[] 반환
     */
    @GetMapping("/tables/{tableName}/fields")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMetaFields(
            @PathVariable String tableName,
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("table_name", tableName);
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(metaService.getMetaFields(params)));
    }

    /**
     * GET /api/meta/tables/{tableName}/relations — 테이블 간 업무 관계 (Phase 5 제어 모드)
     */
    @GetMapping("/tables/{tableName}/relations")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getMetaRelations(
            @PathVariable String tableName,
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("table_name", tableName);
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(metaService.getMetaRelations(params)));
    }
}
