package incheon.ags.pss.edit.web;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import incheon.ags.pss.edit.service.SimulationService;
import incheon.ags.pss.edit.vo.SimulationVO;
import incheon.com.cmm.api.DefaultApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 안건지도 모의실험 관리 컨트롤러
 * @author hj
 */
@Controller
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/pss/edit/simulation")
public class SimulationController {
	@Autowired private ObjectMapper objectMapper;
    private final SimulationService simulationService;

  /**
  * 모의실험 목록 조회 (JSON)
  * @param vo (bizNo, smltTypeCd 필수)
  * @return List<SimulationVO>
  * @throws Exception
  */
    @GetMapping("/list.do")
    @ResponseBody
    public List<SimulationVO> selectSimulationList(SimulationVO vo) throws Exception {
    	return simulationService.selectSimulationList(vo);
    }
    
    /**
     * 모의실험 상세 조회 (JSON)
     * @param smltNo
     * @return SimulationVO
     * @throws Exception
     */
    @GetMapping("/detail.do")
    @ResponseBody
    public Map<String, Object> detailSimulation(@RequestParam Long smltNo) throws Exception {
    	SimulationVO vo = simulationService.selectSimulation(smltNo);

        // 1. VO를 Map으로 변환
        Map<String, Object> responseMap = objectMapper.convertValue(vo, Map.class);
        
        // 2. 문제가 되는 String 필드를 Map(JSON 객체)으로 변환하여 덮어쓰기
        try {
            if (vo.getParamtrInfo() != null) {
                responseMap.put("paramtrInfo", objectMapper.readValue(vo.getParamtrInfo(), Map.class));
            }
            if (vo.getRsltData() != null) {
                responseMap.put("rsltData", objectMapper.readValue(vo.getRsltData(), Map.class));
            }
        } catch (Exception e) {
            // 이미 깨진 데이터(&quot;)가 DB에 있다면 여기서 에러가 날 수 있음
            // 이 경우, DB에서 해당 데이터를 삭제 후 다시 시도해야 함
        	// 문자열 더하기(+) 방식은 민감 정보 노출 위험이 높으므로 플레이스홀더와 예외 객체 사용
            log.error("데이터 변환 처리 중 오류 발생 (JSON)");
            log.debug("JSON 파싱 상세 에러", e);
        }
        
        return responseMap;
    }
    
    @PostMapping("/save.do")
    public ResponseEntity<DefaultApiResponse> insertSimulation(@RequestBody SimulationVO vo) throws Exception {
    	simulationService.insertSimulation(vo);
    	
        return ResponseEntity.ok(
                DefaultApiResponse.success(vo.getSmltNo(), "저장되었습니다.")
            );
    }

    @PostMapping("/update.do")
    public ResponseEntity<DefaultApiResponse> updateSimulation(@RequestBody SimulationVO vo) throws Exception {
    	simulationService.updateSimulation(vo);
        
        return ResponseEntity.ok(
                DefaultApiResponse.success(vo, "수정되었습니다.")
            );
    }
    
    /**
     * 모의실험 삭제
     * @param smltNo 시뮬레이션 번호
     * @return 성공/실패 메시지
     * @throws Exception
     */
    @PostMapping("/delete.do")
    public ResponseEntity<DefaultApiResponse> deleteSimulation(@RequestParam Long smltNo) throws Exception {
        simulationService.deleteSimulation(smltNo);
        
        return ResponseEntity.ok(
                DefaultApiResponse.success(null, "삭제되었습니다.")
            );
    }
}
