package incheon.ags.uis.gisu.web;

import incheon.ags.uis.gisu.service.AdminGisuService;
import incheon.ags.uis.gisu.vo.AdminGisuVO;
import incheon.ags.uis.gisu.vo.GisuSearchVO;
import incheon.com.cmm.context.RequestContext;
import incheon.com.security.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

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

@Slf4j
@Controller
@RequestMapping("/ags/gisu")
public class AdminGisuController {

    private final AdminGisuService service;

    public AdminGisuController(AdminGisuService service) {
        this.service = service;
    }

    @GetMapping("/adminList.do")
    public String adminList(@RequestParam(defaultValue = "1") int page,
                            GisuSearchVO vo,
                            ModelMap model) throws Exception {

        vo.setPageIndex(page);

        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(page);
        paginationInfo.setRecordCountPerPage(vo.getRecordCountPerPage());
        paginationInfo.setPageSize(vo.getPageSize());

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

        int totalCount = service.getAdminGisuListCount(vo);
        paginationInfo.setTotalRecordCount(totalCount);

        List<AdminGisuVO> list = service.getAdminGisuList(vo);

        model.addAttribute("gisuList", list);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("searchVO", vo);

        return "/ags/gisu/adminGisu";
    }


    /** 승인 처리 */
    @PostMapping("/approve.do")
    @ResponseBody
    public Map<String, Object> approve(@RequestParam Long idn) {
        Map<String, Object> res = new HashMap<>();
        try {
            LoginVO admin = RequestContext.getCurrentUser();
            if (admin == null) {
                log.warn("승인 처리 실패 - 로그인 정보 없음: idn={}", idn);
                res.put("success", false);
                res.put("message", "로그인이 필요합니다.");
                return res;
            }

            service.approve(idn, admin.getUserUnqId());
            res.put("success", true);
            res.put("message", "승인 완료");
        } catch (IllegalStateException e) {
            log.warn("승인 처리 실패 - 비즈니스 규칙 위반: idn={}, error={}", idn, e.getMessage());
            res.put("success", false);
            res.put("message", "승인할 수 없는 상태입니다.");
        } catch (IllegalArgumentException e) {
            log.warn("승인 처리 실패 - 잘못된 인자: idn={}, error={}", idn, e.getMessage());
            res.put("success", false);
            res.put("message", "잘못된 요청입니다.");
        } catch (NullPointerException e) {
            log.error("승인 처리 실패 - 필수 값 누락: idn={}", idn, e);
            res.put("success", false);
            res.put("message", "처리 중 오류가 발생했습니다.");
        } catch (Exception e) {
            log.error("승인 처리 중 예상치 못한 오류 발생: idn={}", idn, e);
            res.put("success", false);
            res.put("message", "승인 처리 중 오류가 발생했습니다.");
        }
        return res;
    }

    /** 반려 처리 */
    @PostMapping("/reject.do")
    @ResponseBody
    public Map<String, Object> reject(
            @RequestParam Long idn,
            @RequestParam String rjctRsn
    ) {
        Map<String, Object> res = new HashMap<>();
        try {
            LoginVO admin = RequestContext.getCurrentUser();
            if (admin == null) {
                log.warn("반려 처리 실패 - 로그인 정보 없음: idn={}", idn);
                res.put("success", false);
                res.put("message", "로그인이 필요합니다.");
                return res;
            }

            if (rjctRsn == null || rjctRsn.trim().isEmpty()) {
                log.warn("반려 처리 실패 - 반려사유 없음: idn={}", idn);
                res.put("success", false);
                res.put("message", "반려사유를 입력해주세요.");
                return res;
            }

            service.reject(idn, admin.getUserUnqId(), rjctRsn);
            res.put("success", true);
            res.put("message", "반려 완료");
        } catch (IllegalStateException e) {
            log.warn("반려 처리 실패 - 비즈니스 규칙 위반: idn={}, error={}", idn, e.getMessage());
            res.put("success", false);
            res.put("message", "반려할 수 없는 상태입니다.");
        } catch (IllegalArgumentException e) {
            log.warn("반려 처리 실패 - 잘못된 인자: idn={}, error={}", idn, e.getMessage());
            res.put("success", false);
            res.put("message", "잘못된 요청입니다.");
        } catch (NullPointerException e) {
            log.error("반려 처리 실패 - 필수 값 누락: idn={}", idn, e);
            res.put("success", false);
            res.put("message", "처리 중 오류가 발생했습니다.");
        } catch (Exception e) {
            log.error("반려 처리 중 예상치 못한 오류 발생: idn={}", idn, e);
            res.put("success", false);
            res.put("message", "반려 처리 중 오류가 발생했습니다.");
        }
        return res;
    }
}
