package incheon.ags.ias.tmprUserAuthrt.web;

import incheon.ags.ias.tmprUserAuthrt.service.TmprUserAuthrtService;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.cmm.context.RequestContext;
import incheon.com.cmm.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequiredArgsConstructor
@Slf4j
public class TmprUserAuthrtApiController {

    private final TmprUserAuthrtService tmprUserAuthrtService;

    @PostMapping("/ags/ias/tmprUserAuthrt/insertAuthrtStng.do")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> insertAuthrtStng(
            @RequestBody Map<String, Object> params) throws Exception {

        log.info("권한 설정 추가 요청: {}", params);

        // 현재 로그인 사용자 정보
        String userId = RequestContext.getCurrentUserId();
        if (userId == null) {
            userId = "SYSTEM";
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> stngList = (List<Map<String, Object>>) params.get("stngList");

        if (stngList == null || stngList.isEmpty()) {
            throw new BusinessException("추가할 권한이 없습니다.");
        }

        try {
            int insertCount = tmprUserAuthrtService.insertAuthrtStngBatch(stngList, userId);

            if (insertCount <= 0) {
                throw new BusinessException("권한 설정 추가에 실패했습니다.");
            }

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

            log.info("권한 설정 추가 성공 - 추가 건수: {}", insertCount);
            return ResponseEntity.ok(
                    DefaultApiResponse.success(result, insertCount + "건의 권한 설정이 추가되었습니다.")
            );

        } catch (DuplicateKeyException e) {
            log.error("권한 설정 추가 실패: {}", e.getMessage(), e);
            throw new BusinessException("권한 설정 추가가 중복입니다");
        }
    }

    @PostMapping("/ags/ias/tmprUserAuthrt/updateMenuAuthrt.do")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> updateMenuAuthrt(
            @RequestBody Map<String, Object> params) throws Exception {

        log.info("메뉴 권한 수정 요청: {}", params);

        // 현재 접속한 사용자 ID 설정
        String loginUserId = RequestContext.getCurrentUserId();


        String userId = (String) params.get("userId");
        String roleCd = (String) params.get("roleCd");
        String sysCd = (String) params.get("sysCd");

        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("사용자 정보가 누락되었습니다.");
        }

        if (roleCd == null || roleCd.trim().isEmpty()) {
            throw new BusinessException("역할 정보가 누락되었습니다.");
        }

        if (sysCd == null || sysCd.trim().isEmpty()) {
            throw new BusinessException("시스템 정보가 누락되었습니다.");
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> addMenuList = (List<Map<String, Object>>) params.get("addMenuList");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> deleteMenuList = (List<Map<String, Object>>) params.get("deleteMenuList");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> addSysList = (List<Map<String, Object>>) params.get("addSysList");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> deleteSysList = (List<Map<String, Object>>) params.get("deleteSysList");

        try {
            int addCount = 0;
            int deleteCount = 0;

            // 메뉴 권한 추가
            if (addMenuList != null && !addMenuList.isEmpty()) {
                addCount += tmprUserAuthrtService.insertMenuRoleAuthrtMpngBatch(userId, roleCd, sysCd, addMenuList, loginUserId);
                log.info("메뉴 권한 {}건 추가", addMenuList.size());
            }

            // 메뉴 권한 삭제
            if (deleteMenuList != null && !deleteMenuList.isEmpty()) {
                for (Map<String, Object> mapping : deleteMenuList) {
                    String menuCd = (String) mapping.get("menuCd");
                    String authrtCd = (String) mapping.get("authrtCd");
                    deleteCount += tmprUserAuthrtService.deleteMenuRoleAuthrtMpng(userId, menuCd, roleCd, sysCd, authrtCd);
                }
                log.info("메뉴 권한 {}건 삭제", deleteMenuList.size());
            }

            // 시스템 전역 권한 추가
            if (addSysList != null && !addSysList.isEmpty()) {
                addCount += tmprUserAuthrtService.insertSysRoleAuthrtMpngBatch(userId, roleCd, sysCd, addSysList, loginUserId);
                log.info("시스템 전역 권한 {}건 추가", addSysList.size());
            }

            // 시스템 전역 권한 삭제
            if (deleteSysList != null && !deleteSysList.isEmpty()) {
                for (Map<String, Object> mapping : deleteSysList) {
                    String authrtCd = (String) mapping.get("authrtCd");
                    deleteCount += tmprUserAuthrtService.deleteSysRoleAuthrtMpng(userId, sysCd, roleCd, authrtCd);
                }
                log.info("시스템 전역 권한 {}건 삭제", deleteSysList.size());
            }

            if (addCount == 0 && deleteCount == 0) {
                throw new BusinessException("수정할 권한이 없습니다.");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("addCount", addCount);
            result.put("deleteCount", deleteCount);

            log.info("권한 수정 성공 - 추가: {}건, 삭제: {}건", addCount, deleteCount);
            return ResponseEntity.ok(
                    DefaultApiResponse.success(result,
                            String.format("권한이 수정되었습니다. (추가: %d건, 삭제: %d건)", addCount, deleteCount))
            );

        } catch (DuplicateKeyException e) {
            log.error("권한 수정 실패: {}", e.getMessage(), e);
            throw new BusinessException("권한 설정이 중복입니다");
        }
    }

    @GetMapping("/ags/ias/tmprUserAuthrt/getSysMenuAuthrt.do")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getSysMenuAuthrt(
            @RequestParam String sysCd) throws Exception {

        log.info("시스템 메뉴 권한 조회 요청 - sysCd: {}", sysCd);

        if (sysCd == null || sysCd.trim().isEmpty()) {
            throw new BusinessException("시스템 코드가 필요합니다.");
        }

        // 1. 시스템별 메뉴 목록 조회
        List<Map<String, Object>> menuList = tmprUserAuthrtService.selectMenuListBySysCd(sysCd);

        // 2. 시스템별 메뉴 권한 목록 조회 (메뉴에 할당 가능한 기능권한)
        List<Map<String, Object>> globalMenuAuthrtList = tmprUserAuthrtService.selectMenuAuthrtListBySysCd(sysCd);

        // 3. 시스템 전역 권한 목록 조회 (시스템 전체에 적용되는 권한)
        List<Map<String, Object>> globalSysAuthrtList = tmprUserAuthrtService.selectSysAuthrtListBySysCd(sysCd);

        Map<String, Object> result = new HashMap<>();
        result.put("menuList", menuList);
        result.put("globalMenuAuthrtList", globalMenuAuthrtList);
        result.put("globalSysAuthrtList", globalSysAuthrtList);

        log.info("시스템 메뉴 권한 조회 성공 - 메뉴: {}건, 메뉴권한: {}건, 시스템권한: {}건",
                menuList.size(), globalMenuAuthrtList.size(), globalSysAuthrtList.size());

        return ResponseEntity.ok(
                DefaultApiResponse.success(result, "조회 완료")
        );
    }

    @GetMapping("/ags/ias/tmprUserAuthrt/searchUsers.do")
    public ResponseEntity<DefaultApiResponse<List<Map<String, Object>>>> searchUsers(
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String userNm) throws Exception {

        log.info("사용자 검색 요청 - userId: {}, userNm: {}", userId, userNm);

        // 최소 하나의 검색 조건 확인
        if ((userId == null || userId.trim().isEmpty()) &&
                (userNm == null || userNm.trim().isEmpty())) {
            throw new BusinessException("최소 하나 이상의 검색 조건을 입력해주세요.");
        }

        // 검색 조건 설정
        Map<String, Object> searchParams = new HashMap<>();
        if (userId != null && !userId.trim().isEmpty()) {
            searchParams.put("userId", userId.trim());
        }
        if (userNm != null && !userNm.trim().isEmpty()) {
            searchParams.put("userNm", userNm.trim());
        }

        // 사용자 검색
        List<Map<String, Object>> userList = tmprUserAuthrtService.searchUsers(searchParams);

        log.info("사용자 검색 완료: {} 건", userList.size());

        return ResponseEntity.ok(
                DefaultApiResponse.success(userList, userList.size() + "건의 사용자를 조회했습니다.")
        );
    }

    @PostMapping("/ags/ias/tmprUserAuthrt/insertTmprUserAuthrt.do")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> insertTmprUserAuthrt(
            @RequestBody Map<String, Object> params) throws Exception {

        log.info("임시 사용자 권한 등록 요청: {}", params);

        // 현재 로그인 사용자 정보
        String regUserId = RequestContext.getCurrentUserId();
        if (regUserId == null) {
            regUserId = "SYSTEM";
        }

        // 필수 파라미터 검증
        String userId = (String) params.get("userId");
        String roleBgngYmd = (String) params.get("roleBgngYmd");
        String roleEndYmd = (String) params.get("roleEndYmd");
        String aplcnRsn = (String) params.get("aplcnRsn");
        String sysCd = (String) params.get("sysCd");

        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("사용자 ID가 필요합니다.");
        }

        if (roleBgngYmd == null || roleBgngYmd.trim().isEmpty()) {
            throw new BusinessException("시작일자가 필요합니다.");
        }

        if (roleEndYmd == null || roleEndYmd.trim().isEmpty()) {
            throw new BusinessException("종료일자가 필요합니다.");
        }

        if (sysCd == null || sysCd.trim().isEmpty()) {
            throw new BusinessException("시스템 코드가 필요합니다.");
        }

        // 메뉴 권한 목록
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> menuAuthrtList = (List<Map<String, Object>>) params.get("menuAuthrtList");

        // 시스템 권한 목록
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> sysAuthrtList = (List<Map<String, Object>>) params.get("sysAuthrtList");

        try {
            String roleCd = "ROLE_TMPR_" + sysCd;

            // 1. 임시 사용자 권한 기본 정보 등록
            Map<String, Object> authrtParams = new HashMap<>();
            authrtParams.put("userId", userId);
            authrtParams.put("sysCd", sysCd);
            authrtParams.put("roleBgngYmd", roleBgngYmd);
            authrtParams.put("roleEndYmd", roleEndYmd);
            authrtParams.put("aplcnRsn", aplcnRsn);
            authrtParams.put("regUserId", regUserId);
            authrtParams.put("mdfcnUserId", regUserId);
            authrtParams.put("roleCd", roleCd);

            int result = tmprUserAuthrtService.insertTmprUserAuthrt(authrtParams);

            if (result <= 0) {
                throw new BusinessException("임시 사용자 권한 등록에 실패했습니다.");
            }

            // 2. 메뉴 권한 매핑 등록
            int menuAuthrtCount = 0;
            if (menuAuthrtList != null && !menuAuthrtList.isEmpty()) {
                menuAuthrtCount = tmprUserAuthrtService.insertMenuRoleAuthrtMpngBatch(
                        userId, roleCd, sysCd, menuAuthrtList, regUserId
                );
                log.info("메뉴 권한 {}건 등록", menuAuthrtCount);
            }

            // 3. 시스템 권한 매핑 등록
            int sysAuthrtCount = 0;
            if (sysAuthrtList != null && !sysAuthrtList.isEmpty()) {
                sysAuthrtCount = tmprUserAuthrtService.insertSysRoleAuthrtMpngBatch(
                        userId, roleCd, sysCd, sysAuthrtList, regUserId
                );
                log.info("시스템 권한 {}건 등록", sysAuthrtCount);
            }

            Map<String, Object> resultData = new HashMap<>();
            resultData.put("userId", userId);
            resultData.put("menuAuthrtCount", menuAuthrtCount);
            resultData.put("sysAuthrtCount", sysAuthrtCount);
            resultData.put("totalCount", menuAuthrtCount + sysAuthrtCount);

            log.info("임시 사용자 권한 등록 성공 - userId: {}, 메뉴권한: {}건, 시스템권한: {}건",
                    userId, menuAuthrtCount, sysAuthrtCount);

            return ResponseEntity.ok(
                    DefaultApiResponse.success(resultData,
                            String.format("임시 사용자 권한이 등록되었습니다. (메뉴권한: %d건, 시스템권한: %d건)",
                                    menuAuthrtCount, sysAuthrtCount))
            );

        } catch (DuplicateKeyException e) {
            log.error("임시 사용자 권한 등록 실패 - 중복: {}", e.getMessage(), e);
            throw new BusinessException("이미 등록된 임시 사용자 권한입니다.");
        }
    }

    @DeleteMapping("/ags/ias/tmprUserAuthrt/deleteTmprUserAuthrt.do/{userId}")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> deleteTmprUserAuthrt(
            @PathVariable("userId") String userId,
            @RequestParam("roleCd") String roleCd,
            @RequestParam("sysCd") String sysCd) throws Exception {

        log.info("임시 사용자 권한 삭제 요청 - 사용자ID: {}, 역할코드: {}", userId, roleCd);

        if (userId == null || userId.trim().isEmpty()) {
            throw new BusinessException("삭제할 사용자 ID가 없습니다.");
        }

        if (roleCd == null || roleCd.trim().isEmpty()) {
            throw new BusinessException("삭제할 역할 코드가 없습니다.");
        }

        if (sysCd == null || sysCd.trim().isEmpty()) {
            throw new BusinessException("삭제할 시스템 코드 정보가 없습니다.");
        }

        try {
            // 해당 시스템의 임시 권한만 삭제 (상세 정보 포함)
            Map<String, Object> deleteResult = tmprUserAuthrtService.deleteTmprUserAuthrtByUserIdAndRoleCdWithDetail(userId, roleCd, sysCd);

            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.putAll(deleteResult);

            int totalCount = (Integer) deleteResult.get("totalCount");
            int actualAuthrtCount = (Integer) deleteResult.get("actualAuthrtCount");
            int menuAuthrtCount = (Integer) deleteResult.get("menuAuthrtCount");
            int sysAuthrtCount = (Integer) deleteResult.get("sysAuthrtCount");

            log.info("임시 사용자 권한 삭제 성공 - 사용자ID: {}, 역할코드: {}, 총 삭제: {}건 (메뉴권한: {}건, 시스템권한: {}건)",
                    userId, roleCd, totalCount, menuAuthrtCount, sysAuthrtCount);

            String message = String.format("임시 권한이 삭제되었습니다.\n" +
                    "• 실제 권한: %d개\n" +
                    "• 메뉴 권한: %d개\n" +
                    "• 시스템 권한: %d개\n" +
                    "• 총 삭제: %d건", 
                    actualAuthrtCount, menuAuthrtCount, sysAuthrtCount, totalCount);

            return ResponseEntity.ok(
                    DefaultApiResponse.success(result, message)
            );

        } catch (Exception e) {
            log.error("임시 사용자 권한 삭제 실패 - 사용자ID: {}, 오류: {}", userId, e.getMessage(), e);
            throw new BusinessException("임시 사용자 권한 삭제에 실패했습니다.");
        }
    }

}