package incheon.ags.ias.sysMenuAuthrt.web;

import incheon.ags.ias.sysMenuAuthrt.service.SysMenuAuthrtService;
import incheon.ags.ias.sysMenuAuthrt.vo.SysMenuAuthrtSearchVO;
import incheon.com.security.annotation.RequireRole;
import incheon.com.security.util.SecurityUtil;
import incheon.com.security.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
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.RequestParam;

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

@Controller
@RequiredArgsConstructor
@Slf4j
@RequireRole(system = "AGS", roles = {"ROLE_SUPER_ADMIN", "ROLE_AGS_ADMIN"}, description = "통합관리자 역할 접근 제어")
public class SysMenuAuthrtController {
    private final SysMenuAuthrtService sysMenuAuthrtService;

    @GetMapping({"/ags/ias/sysMenuAuthrt/sysMenuAuthrtList.do", "/ags/ias/authrt/authrtSetMng/list.do"})
    public String sysMenuAuthrtList(
            @RequestParam(defaultValue = "1") int page,
            @ModelAttribute SysMenuAuthrtSearchVO searchVO,
            ModelMap model) throws Exception {

        log.info("=== sysMenuAuthrtList 조회 시작 ===");
        log.info("검색 조건 - searchSysCd: {}, searchRoleNm: {}, searchRoleTypeCd: {}, useYn: {}",
                 searchVO.getSearchSysCd(), searchVO.getSearchRoleNm(), searchVO.getSearchRoleTypeCd(), searchVO.getUseYn());

        // 권한 필터링: 통합관리자는 전체, 업무관리자는 해당 시스템만, 그 외는 조회 불가
        LoginVO loginVO = SecurityUtil.getCurrentUser();
        log.info("=== 권한 필터링 디버그 ===");
        log.info("loginVO: {}, isSuperAdmin: {}, adminSysCds: {}",
                 loginVO != null ? loginVO.getUserId() : "null",
                 loginVO != null ? loginVO.isSuperAdmin() : "null",
                 loginVO != null ? loginVO.getAdminSysCds() : "null");

        boolean hasAdminAuthrt = true;
        if (loginVO != null && !loginVO.isSuperAdmin()) {
            List<String> adminSysCds = loginVO.getAdminSysCds();
            if (adminSysCds != null && !adminSysCds.isEmpty()) {
                // 업무관리자: 해당 시스템만 조회
                searchVO.setSysCdList(adminSysCds);
                log.info("업무관리자 필터링 적용 - 시스템 코드: {}", adminSysCds);
            } else {
                // 일반 사용자: 조회 권한 없음
                hasAdminAuthrt = false;
                log.info("일반 사용자 - 조회 권한 없음");
            }
        }

        // 페이징 설정
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setRecordCountPerPage(searchVO.getRecordCountPerPage());
        paginationInfo.setPageSize(searchVO.getPageSize());

        int totalCount = 0;
        List<Map<String, Object>> sysMenuAuthrtList = List.of();

        if (hasAdminAuthrt) {
            // 권한이 있는 경우만 조회
            totalCount = sysMenuAuthrtService.selectSysMenuAuthrtListCnt(searchVO);

            // 페이지 번호 보정 (totalCount 기준)
            int maxPage = (int) Math.ceil((double) totalCount / searchVO.getRecordCountPerPage());
            if (maxPage > 0 && page > maxPage) {
                page = maxPage;
            }
            if (page < 1) page = 1;

            searchVO.setPageIndex(page);
            paginationInfo.setCurrentPageNo(page);
            searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
            searchVO.setLastIndex(paginationInfo.getLastRecordIndex());

            sysMenuAuthrtList = sysMenuAuthrtService.selectSysMenuAuthrtList(searchVO);
        } else {
            // 권한 없으면 빈 결과
            page = 1;
            paginationInfo.setCurrentPageNo(page);
        }

        log.info("총 건수: {}", totalCount);
        paginationInfo.setTotalRecordCount(totalCount);

        model.addAttribute("totalCount", totalCount);
        model.addAttribute("sysMenuAuthrtList", sysMenuAuthrtList);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("searchVO", searchVO);

        // 시스템 목록 조회
        List<Map<String, Object>> systemList = sysMenuAuthrtService.selectSystemList();
        model.addAttribute("systemList", systemList);

        return "ags/ias/sysMenuAuthrt/sysMenuAuthrtList";
    }

    @GetMapping({"/ags/ias/sysMenuAuthrt/sysMenuAuthrtDetail.do", "/ags/ias/authrt/authrtSetMng/detail.do"})
    public String sysMenuAuthrtDetail(
            @RequestParam String roleCd,
            @RequestParam String sysCd,
            ModelMap model) throws Exception {

        // 역할 정보 조회 (ROLE_CD + SYS_CD 복합키)
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("roleCd", roleCd);
        params.put("sysCd", sysCd);
        Map<String, Object> roleInfo = sysMenuAuthrtService.selectRoleInfo(params);
        model.addAttribute("roleInfo", roleInfo);

        // 해당 역할의 메뉴-권한 매핑 조회
        List<Map<String, Object>> menuAuthrtList = sysMenuAuthrtService.selectSysMenuAuthrtByRoleCd(params);
        model.addAttribute("menuAuthrtList", menuAuthrtList);

        // 해당 역할의 시스템-권한 매핑 조회
        List<Map<String, Object>> sysAuthrtList = sysMenuAuthrtService.selectSysRoleAuthrtByRoleCd(params);
        model.addAttribute("sysAuthrtList", sysAuthrtList);

        return "ags/ias/sysMenuAuthrt/sysMenuAuthrtDetail";
    }

    @GetMapping({"/ags/ias/sysMenuAuthrt/sysMenuAuthrtModify.do", "/ags/ias/authrt/authrtSetMng/modify.do"})
    public String sysMenuAuthrtModify(
            @RequestParam String roleCd,
            @RequestParam String sysCd,
            ModelMap model) throws Exception {

        // 역할 정보 조회 (ROLE_CD + SYS_CD 복합키)
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("roleCd", roleCd);
        params.put("sysCd", sysCd);
        Map<String, Object> roleInfo = sysMenuAuthrtService.selectRoleInfo(params);
        model.addAttribute("roleInfo", roleInfo);

        // 기존 메뉴-권한 매핑 조회
        List<Map<String, Object>> menuAuthrtList = sysMenuAuthrtService.selectSysMenuAuthrtByRoleCd(params);
        model.addAttribute("menuAuthrtList", menuAuthrtList);

        // 기존 시스템-권한 매핑 조회
        List<Map<String, Object>> sysAuthrtList = sysMenuAuthrtService.selectSysRoleAuthrtByRoleCd(params);
        model.addAttribute("sysAuthrtList", sysAuthrtList);

        return "ags/ias/sysMenuAuthrt/sysMenuAuthrtModify";
    }
}
