package incheon.ags.dss.status.web;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import incheon.com.cmm.api.DefaultApiResponse;
import incheon.ags.dss.status.service.AnaLgdFomService;
import incheon.ags.dss.status.vo.AnaLgdFomMstVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Tag(name = "분석-범례(Legend)", description = "통계지도 시각화를 위한 범례 설정 관리 API")
@RestController 
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/v1/dss/ana/legend")
public class AnaLgdFomApiController {

    private final AnaLgdFomService anaLgdFomService;

    @Operation(summary = "범례 상세 조회", description = "수정 폼에 바인딩할 범례 마스터 및 상세 정보를 조회합니다.")
    @GetMapping("/detail.do")
    public ResponseEntity<DefaultApiResponse> getDetail(
            @Parameter(description = "범례형식번호", required = true, example = "1") 
            @RequestParam("lgdFrmNo") int lgdFrmNo) throws Exception {
        
        AnaLgdFomMstVO result = anaLgdFomService.selectAnaLgdFomDetail(lgdFrmNo);
        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }

    @Operation(summary = "지도 엔진용 JSON 설정 조회", description = "OpenLayers/Leaflet 등 지도 엔진에 즉시 적용 가능한 JSON 구조를 반환합니다.")
    @GetMapping("/config.do")
    public ResponseEntity<DefaultApiResponse> getConfig(
            @Parameter(description = "범례형식번호", required = true, example = "1") 
            @RequestParam("lgdFrmNo") int lgdFrmNo) throws Exception {
        
        // DB에서 완성된 JSON 객체를 가져옴
        Map<String, Object> config = anaLgdFomService.selectLegendConfigJson(lgdFrmNo);
        
        // PostgreSQL JSON 컬럼이 MyBatis Map으로 반환될 때의 Key 확인 필요 ("jsonResult")
        Object jsonResult = config != null ? config.get("jsonResult") : null;
        
        return ResponseEntity.ok(DefaultApiResponse.success(jsonResult, "설정 조회 성공"));
    }

    @Operation(summary = "범례 설정 저장", description = "범례 마스터 정보와 구간(Detail) 정보를 등록하거나 수정합니다.")
    @PostMapping("/save.do")
    public ResponseEntity<DefaultApiResponse> save(
            @RequestBody AnaLgdFomMstVO vo,
            HttpServletRequest request) throws Exception {
        
        int lgdFrmNo = anaLgdFomService.saveAnaLgdFom(vo);
        
        Map<String, Object> result = new HashMap<>();
        result.put("lgdFrmNo", lgdFrmNo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "저장되었습니다."));
    }
}