package incheon.ags.dss.facility.web;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;
import incheon.com.cmm.ComDefaultVO;
import incheon.com.cmm.api.DefaultApiResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import incheon.ags.dss.facility.service.FacHistoryService;
import incheon.ags.dss.facility.vo.SafetyInspectionVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RestController 
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/v1/dss/facility/history")
public class FacHistoryApiController {

    private final FacHistoryService facHistoryService;

    /**
     * BLCM 안전진단 이력 화면 호출을 위한 파라미터 조회
     * - 좌표(경도/위도, EPSG:4326) 기반 우선
     * - 하위 호환을 위해 PNU 기반도 지원
     */
    @GetMapping("/blcmHistTarget.do")
    public ResponseEntity<DefaultApiResponse> getBlcmHistTargetList(
            @RequestParam(value = "longitude", required = false) Double longitude,
            @RequestParam(value = "latitude", required = false) Double latitude,
            @RequestParam(value = "pnu", required = false) String pnu
    ) throws Exception {

        final boolean hasCoord = (longitude != null && latitude != null);
        final boolean hasPnu = StringUtils.hasText(pnu);

        if (!hasCoord && !hasPnu) {
            return ResponseEntity.badRequest().body(DefaultApiResponse.error(400, "좌표(longitude/latitude) 또는 PNU 값이 없습니다.", ""));
        }

        List<Map<String, Object>> list = hasCoord
                ? facHistoryService.selectBlcmHistTargetListByCoord(longitude, latitude)
                : facHistoryService.selectBlcmHistTargetListByPnu(pnu);

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("searchType", "B");

        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }

    /**
     * 20p: 안전진단 이력 (JSON)
     */
    @GetMapping("/safety.do")
    public ResponseEntity<DefaultApiResponse> getSafetyInspection(
            @RequestParam(value = "searchKeyword") String searchKeyword, // (bldgPk)
            @RequestParam(value = "year", required = false) String year 
        ) throws Exception {
        
        log.info("API: getSafetyInspection (PK: {}, Year: {})", searchKeyword, year);
        
        SafetyInspectionVO searchVO = new SafetyInspectionVO();
        searchVO.setSearchKeyword(searchKeyword);
        
        List<String> yearList = facHistoryService.selectSafetyInspectionYearList(searchVO);

        String targetYear = StringUtils.hasText(year) ? year : 
                           (yearList != null && !yearList.isEmpty() ? yearList.get(0) : String.valueOf(LocalDate.now().getYear()));
        
        searchVO.setYear(targetYear); 
        SafetyInspectionVO detailData = facHistoryService.selectSafetyInspectionDetail(searchVO);
        
        log.info("API: detailData ({})", detailData);
        
        Map<String, Object> result = new HashMap<>();
        result.put("yearList", yearList);
        result.put("detailData", detailData);
        result.put("currentYear", targetYear);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "안전진단 이력이 조회되었습니다."));
    }
}