package com.eactive.eai.rms.ext.djb.statistics;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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 com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.ext.kjb.statistics.ui.ApiStatsSearch;
import com.eactive.ext.kjb.statistics.ui.ApiStatsUI;

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

@Slf4j
@Controller
@RequiredArgsConstructor
public class ApiUseStatsController {

	private final ApiUseStatsService service;
	private final ApiUseStatsExcelExportService excelExportService;

	@GetMapping(value = "/onl/kjb/statistics/apiUseStatsMan.view")
	public String view() {
		return "/onl/kjb/statistics/apiUseStatsMan";
	}

	@PostMapping(value = "/onl/kjb/statistics/apiUseStatsMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<ApiStatsUI>> selectList(ApiStatsSearch search, Pageable pageable) {
		Page<ApiStatsUI> page = service.selectList(search, pageable);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value = "/onl/kjb/statistics/apiUseStatsMan.json", params = "cmd=EXCEL_EXPORT")
	public void exportToExcel(ApiStatsSearch search, HttpServletResponse response) throws IOException {
		log.info("Excel export started - search: {}", search);

		try {
			List<ApiStatsUI> uiList = service.selectList(search);
			log.info("Data retrieved - count: {}", uiList.size());

			if (uiList.isEmpty()) {
				log.warn("No data found for export");
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				response.setContentType("application/json; charset=UTF-8");
				response.getWriter().write("{\"message\":\"조회된 데이터가 없습니다.\"}");
				response.getWriter().flush();
				return;
			}

			String fileName = generateFileName(search);
			log.info("Generating Excel file: {}", fileName);

			excelExportService.exportApiStats(uiList, fileName, response);
			log.info("Excel export completed successfully");

		} catch (Exception e) {
			log.error("Excel export failed - error: {}", e.getMessage(), e);

			if (!response.isCommitted()) {
				response.reset();
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				response.setContentType("application/json; charset=UTF-8");
				response.getWriter().write("{\"message\":\"Excel 파일 생성 중 오류가 발생했습니다: " + e.getMessage() + "\"}");
				response.getWriter().flush();
			} else {
				log.error("Cannot send error response - response already committed");
			}
		}
	}
	
	private String generateFileName(ApiStatsSearch search) {
		return "API사용현황_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
	}

}
