package com.erp.controller;

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

    private final MapDataService mapDataService;

    /**
     * 외부 DB에서 지도 데이터 조회
     * GET /api/map-data/external/:connectionId
     * query params: tableName(필수), latColumn(필수), lngColumn(필수),
     *               labelColumn, statusColumn, additionalColumns(쉼표구분), whereClause
     */
    @GetMapping("/external/{connectionId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getExternalMapData(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long connectionId,
            @RequestParam Map<String, Object> params) {

        String tableName = (String) params.get("table_name");
        String latColumn = (String) params.get("lat_column");
        String lngColumn = (String) params.get("lng_column");

        if (tableName == null || tableName.isBlank()
                || latColumn == null || latColumn.isBlank()
                || lngColumn == null || lngColumn.isBlank()) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("tableName, latColumn, lngColumn은 필수입니다."));
        }

        Map<String, Object> data = mapDataService.getExternalMapData(connectionId, params);
        return ResponseEntity.ok(ApiResponse.success(data));
    }

    /**
     * 내부 DB에서 지도 데이터 조회
     * GET /api/map-data/internal
     * query params: tableName(필수), latColumn(필수), lngColumn(필수),
     *               labelColumn, statusColumn, additionalColumns(쉼표구분), whereClause
     */
    @GetMapping("/internal")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getInternalMapData(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {

        String tableName = (String) params.get("table_name");
        String latColumn = (String) params.get("lat_column");
        String lngColumn = (String) params.get("lng_column");

        if (tableName == null || tableName.isBlank()
                || latColumn == null || latColumn.isBlank()
                || lngColumn == null || lngColumn.isBlank()) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("tableName, latColumn, lngColumn은 필수입니다."));
        }

        Map<String, Object> data = mapDataService.getInternalMapData(params);
        return ResponseEntity.ok(ApiResponse.success(data));
    }
}
