package incheon.ags.ias.rst.link.web;



import java.util.HashMap;
import java.util.Map;

import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;

import incheon.ags.ias.rst.link.service.AgsRstLinkService;
import incheon.ags.ias.rst.link.service.AgsRstPlmvService;
import incheon.ags.ias.rst.link.service.AgsRstPpltnService;
import incheon.ags.ias.rst.link.vo.AgsRstLinkSearchVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName : AgsRstLinkController.java
 * @Description : 부동산통계 API 연계 컨트롤러
 *
 * @author : 이주훈
 * @since : 2025. 11. 04
 * @version : 1.0
 *
 */
@Slf4j
@Controller
@RequestMapping("/ags/ias/rst")
@RequiredArgsConstructor
public class AgsRstLinkController {
	
	private final AgsRstLinkService agsRstLinkService;
	private final AgsRstPlmvService agsRstPlmvService;
	private final AgsRstPpltnService agsRstPpltnService;
	
    /**
     * 한국부동산원 API 데이터를 호출하여 DB에 저장 (전체 적재)
     */
	@GetMapping("/insertVoluStatsAll.do")
	@ResponseBody
	public Map<String, Object> insertVoluStatsAll(@RequestParam(defaultValue = "1000") int pageSize) {
	    Map<String, Object> result = new HashMap<>();
	    try {
	        Map<String, Object> stats = agsRstLinkService.insertVoluStatsAll(pageSize);
	        result.putAll(stats);
	        result.put("success", true);
	    } catch (RestClientException e) {
            log.error("한국부동산원 API 호출 중 통신 오류 발생");
            result.put("success", false);
            result.put("message", "한국부동산원 API 서버와의 통신 중 오류가 발생했습니다.");
        } catch (DataAccessException e) {
            log.error("한국부동산원 데이터 전체 적재 중 DB 오류 발생");
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");
        }
	    
	    return result;
	}
	
    /**
     * 한국부동산원 API 데이터를 호출하여 DB에 저장 (증가분 적재)
     */
	@GetMapping("/insertVoluStatsIncremental.do")
	@ResponseBody
	public Map<String, Object> insertVoluStatsIncremental(@RequestParam(defaultValue = "1000") int pageSize) {
	    Map<String, Object> result = new HashMap<>();
	    try {
	        Map<String, Object> stats = agsRstLinkService.insertVoluStatsIncremental(pageSize);
	        result.putAll(stats);
	        result.put("success", true);
	    } catch (RestClientException e) {
            log.error("한국부동산원 증분 API 호출 중 통신 오류 발생");
            result.put("success", false);
            result.put("message", "한국부동산원 API 서버와의 통신 중 오류가 발생했습니다.");
        } catch (DataAccessException e) {
            log.error("한국부동산원 증분 데이터 적재 중 DB 오류 발생");
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");
        }
	    
	    return result;
	}
	
    /**
     * 국가데이터처(KOSIS) API 데이터를 호출하여 DB에 저장 (전체 적재)
     */
	@GetMapping("/insertPpltnStatsAll.do")
	@ResponseBody
	public Map<String, Object> insertPpltnStatsAll() {
	    Map<String, Object> result = new HashMap<>();
	    try {
	    	Map<String, Object> results = agsRstLinkService.insertPpltnStatsAll();
	    	result.putAll(results);
	        result.put("success", true);
	    } catch (RestClientException e) {
            log.error("KOSIS API 호출 중 통신 오류 발생");
            result.put("success", false);
            result.put("message", "KOSIS API 서버 통신 오류가 발생했습니다.");
        } catch (DataAccessException e) {
            log.error("KOSIS 데이터 전체 적재 중 DB 오류 발생");
            result.put("success", false);
            result.put("message", "데이터베이스 저장 중 오류가 발생했습니다.");
        }
	    
	    return result;
	}
	
	/**
	 * 국가데이터처(KOSIS) API 데이터를 호출하여 DB에 저장 (증가분 적재)
	 */
	@GetMapping("/insertPpltnStatsIncremental.do")
	@ResponseBody
	public Map<String, Object> insertPpltnStatsIncremental() {
	    Map<String, Object> result = new HashMap<>();
	    try {
	        Map<String, Object> results = agsRstLinkService.insertPpltnStatsIncremental();
	        result.putAll(results);
	        result.put("success", true);
	    } catch (RestClientException e) {
            log.error("KOSIS 증분 API 호출 중 통신 오류 발생");
            result.put("success", false);
            result.put("message", "KOSIS API 서버 통신 오류가 발생했습니다.");
        } catch (DataAccessException e) {
            log.error("KOSIS 증분 데이터 적재 중 DB 오류 발생");
            result.put("success", false);
            result.put("message", "데이터베이스 저장 중 오류가 발생했습니다.");
        }
	    
	    return result;
	}
	
	/**
	 * 부동산통계 API 연계 목록 화면
	 */
    @GetMapping("/linkDataList.do")
    public String linkDataList(
        @RequestParam(defaultValue = "1") int page,
        @ModelAttribute AgsRstLinkSearchVO vo,  
        ModelMap model) throws Exception {

        model.addAttribute("headerTitle", "부동산통계 API 연계");

        // 기본 페이징 설정
        int totalCount = 1;
        vo.setPageIndex(page);
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(page);
        paginationInfo.setRecordCountPerPage(10);
        paginationInfo.setPageSize(10);

        vo.setFirstIndex(paginationInfo.getFirstRecordIndex());
        vo.setLastIndex(paginationInfo.getLastRecordIndex());
        vo.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

        paginationInfo.setTotalRecordCount(totalCount);

        // Model
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("totalCount", totalCount);

        return "ags/ias/rst/link/linkDataList";
    }
    
    /**
     * 전세 + 매매 실거래 데이터 적재 (전세가율 통계 테이블 : icrst.rst_prc_stats)
     */
    @GetMapping("/insertPrcStatsAll.do")
    @ResponseBody
    public Map<String, Object> insertPrcStatsAll() {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = agsRstLinkService.insertPrcStatsAll();
            result.put("success", true);
            result.put("insertCount", count);
        } catch (DataAccessException e) {
            log.error("실거래 통계 데이터(PrcStats) 적재 중 DB 오류 발생");
            result.put("success", false);
            result.put("message", "데이터베이스 적재 처리 중 오류가 발생했습니다.");
        } 
        
        return result;
    }
    
    /**
     * 행정안전부 인구이동통계 전체 적재
     */
    @GetMapping("/insertPlmvStatsAll.do")
    @ResponseBody
    public Map<String, Object> insertPlmvStatsAll() {

        Map<String, Object> result = new HashMap<>();

        try {
            Map<String, Object> stats = agsRstPlmvService.insertPlmvStatsAll();
            result.putAll(stats);
            result.put("success", true);

        } catch (RestClientException e) {
            log.error("행정안전부 API 호출 중 통신 오류 발생", e);
            result.put("success", false);
            result.put("message", "행정안전부 API 서버와의 통신 중 오류가 발생했습니다.");

        } catch (DataAccessException e) {
            log.error("행정안전부 인구이동 전체 적재 중 DB 오류 발생", e);
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");

        } catch (Exception e) {
            log.error("행정안전부 인구이동 전체 적재 중 알 수 없는 오류", e);
            result.put("success", false);
            result.put("message", "처리 중 알 수 없는 오류가 발생했습니다.");
        }

        return result;
    }


    /**
     * 행정안전부 인구이동통계 증분 적재
     */
    @GetMapping("/insertPlmvStatsIncremental.do")
    @ResponseBody
    public Map<String, Object> insertPlmvStatsIncremental() {

        Map<String, Object> result = new HashMap<>();

        try {
            Map<String, Object> stats = agsRstPlmvService.insertPlmvStatsIncremental();
            result.putAll(stats);
            result.put("success", true);

        } catch (RestClientException e) {
            log.error("행정안전부 증분 API 호출 중 통신 오류 발생", e);
            result.put("success", false);
            result.put("message", "행정안전부 API 서버와의 통신 중 오류가 발생했습니다.");

        } catch (DataAccessException e) {
            log.error("행정안전부 증분 데이터 적재 중 DB 오류 발생", e);
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");

        } catch (Exception e) {
            log.error("행정안전부 증분 적재 중 알 수 없는 오류", e);
            result.put("success", false);
            result.put("message", "처리 중 알 수 없는 오류가 발생했습니다.");
        }

        return result;
    }
    
    /**
     * 행정안전부 인구현황통계 전체 적재
     */
    @GetMapping("/insertRegPpltnStatsAll.do")
    @ResponseBody
    public Map<String, Object> insertRegPpltnStatsAll(@RequestParam("level") String level) {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> stats = agsRstPpltnService.insertPpltnStatsAll(level);
            result.putAll(stats);
            result.put("success", true);
        } catch (RestClientException e) {
            log.error("행정안전부 인구현황 API 호출 중 통신 오류 발생", e);
            result.put("success", false);
            result.put("message", "행정안전부 API 서버와의 통신 중 오류가 발생했습니다.");

        } catch (DataAccessException e) {
            log.error("행정안전부 인구현황 전체 적재 중 DB 오류 발생", e);
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");

        } catch (Exception e) {
            log.error("행정안전부 인구현황 전체 적재 중 알 수 없는 오류", e);
            result.put("success", false);
            result.put("message", "처리 중 알 수 없는 오류가 발생했습니다.");
        }
        return result;
    }
    
    /**
     * 행정안전부 인구현황통계 증분 적재
     */
    @GetMapping("/insertRegPpltnStatsIncremental.do")
    @ResponseBody
    public Map<String, Object> insertRegPpltnStatsIncremental(@RequestParam("level") String level) { 
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> stats = agsRstPpltnService.insertPpltnStatsIncremental(level);
            result.putAll(stats);
            result.put("success", true);
        } catch (RestClientException e) {
            log.error("행정안전부 인구현황 증분 API 호출 중 통신 오류 발생", e);
            result.put("success", false);
            result.put("message", "행정안전부 API 서버와의 통신 중 오류가 발생했습니다.");

        } catch (DataAccessException e) {
            log.error("행정안전부 인구현황 증분 적재 중 DB 오류 발생", e);
            result.put("success", false);
            result.put("message", "데이터베이스 처리 중 오류가 발생했습니다.");

        } catch (Exception e) {
            log.error("행정안전부 인구현황 증분 적재 중 알 수 없는 오류", e);
            result.put("success", false);
            result.put("message", "처리 중 알 수 없는 오류가 발생했습니다.");
        }
        return result;
    }
    
}
    
