package incheon.ags.ias.authrt.service.impl;

import incheon.ags.ias.authrt.mapper.AuthrtMapper;
import incheon.ags.ias.authrt.service.AuthrtService;
import incheon.ags.ias.authrt.vo.AuthrtSearchVO;
import incheon.ags.ias.authrt.vo.AuthrtVO;
import incheon.ags.ias.sysMenuAuthrt.mapper.SysMenuAuthrtMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service("AuthService")
@RequiredArgsConstructor
public class AuthrtServiceImpl extends EgovAbstractServiceImpl implements AuthrtService {
    private final AuthrtMapper authrtMapper;
    private final SysMenuAuthrtMapper sysMenuAuthrtMapper;

    @Override
    public List<Map<String, Object>> selectAuthrtList(AuthrtSearchVO authVO) throws Exception{
        log.debug("권한 목록 조회 요청 - 검색조건: {}", authVO);
        List<Map<String, Object>> result = authrtMapper.selectAuthrtList(authVO);
        log.debug("권한 목록 조회 완료 - 조회건수: {}", result.size());
        return result;
    }

    @Override
    public List<Map<String, Object>> selectSysList() throws Exception{
        log.debug("시스템 목록 조회 요청");
        return authrtMapper.selectSysList();
    }

    @Override
    public List<Map<String, Object>> selectAuthrtTypeList() throws Exception{
        log.debug("권한 유형 목록 조회 요청");
        return authrtMapper.selectAuthrtTypeList();
    }

    @Override
    public AuthrtVO selectAuthrtDetail(AuthrtVO authrtVO) throws Exception{
        log.debug("권한 상세 조회 요청 - 권한코드: {}", authrtVO.getAuthrtCd());
        AuthrtVO result = authrtMapper.selectAuthrtDetail(authrtVO);
        if (result == null) {
            log.warn("권한 상세 조회 실패 - 권한을 찾을 수 없음: {}", authrtVO.getAuthrtCd());
        }
        return result;
    }

    @Override
    public int selectAuthrtListCnt(AuthrtSearchVO authrtSearchVO) throws Exception{
        log.debug("권한 목록 총 개수 조회 요청");
        return authrtMapper.selectAuthrtListCnt(authrtSearchVO);
    }

    @Override
    @Transactional
    public int insertAuthrt(AuthrtVO authrtVO) throws Exception{
        log.info("권한 등록 요청 - 권한코드: {}, 권한명: {}", authrtVO.getAuthrtCd(), authrtVO.getAuthrtNm());

        if (authrtVO == null || authrtVO.getAuthrtCd() == null) {
            log.error("권한 등록 실패 - 필수 파라미터 누락");
            throw new IllegalArgumentException("권한 정보가 올바르지 않습니다.");
        }

        int result = authrtMapper.insertAuthrt(authrtVO);

        if (result > 0) {
            log.info("권한 등록 성공 - 권한코드: {}", authrtVO.getAuthrtCd());
        } else {
            log.error("권한 등록 실패 - 권한코드: {}", authrtVO.getAuthrtCd());
        }

        return result;
    }

    @Override
    @Transactional
    public int updateAuthrt(AuthrtVO authrtVO) throws Exception{
        log.info("권한 수정 요청 - 권한코드: {}", authrtVO.getAuthrtCd());

        if (authrtVO == null || authrtVO.getAuthrtCd() == null) {
            log.error("권한 수정 실패 - 필수 파라미터 누락");
            throw new IllegalArgumentException("권한 정보가 올바르지 않습니다.");
        }

        int result = authrtMapper.updateAuthrt(authrtVO);

        if (result > 0) {
            log.info("권한 수정 성공 - 권한코드: {}", authrtVO.getAuthrtCd());
        } else {
            log.warn("권한 수정 실패 - 권한을 찾을 수 없음: {}", authrtVO.getAuthrtCd());
        }

        return result;
    }

    @Override
    @Transactional
    public int deleteAuthrt(AuthrtVO authrtVO) throws Exception{
        log.info("권한 삭제 요청 - 권한코드: ({}, {})", authrtVO.getAuthrtCd(), authrtVO.getSysCd());

        if (authrtVO == null || authrtVO.getAuthrtCd() == null || authrtVO.getSysCd() == null) {
            log.error("권한 삭제 실패 - 필수 파라미터 누락 (AUTHRT_CD, SYS_CD 필수)");
            throw new IllegalArgumentException("권한 코드가 올바르지 않습니다. (AUTHRT_CD, SYS_CD 필수)");
        }

        // AUTHRT 테이블 삭제 - FK ON DELETE CASCADE에 의해 모든 연관 테이블 자동 삭제됨
        // 연관 테이블 (5개):
        // - MENU_ROLE_AUTHRT_MPNG
        // - SYS_ROLE_AUTHRT_MPNG
        // - AUTHRT_STNG
        // - TMPR_USER_AUTHRT_MENU_MPNG
        // - TMPR_USER_AUTHRT_SYS_MPNG
        int result = authrtMapper.deleteAuthrt(authrtVO);

        if (result > 0) {
            log.info("권한 삭제 성공 - 권한코드: ({}, {}) (FK CASCADE로 5개 연관 테이블 자동 삭제)",
                     authrtVO.getAuthrtCd(), authrtVO.getSysCd());
        } else {
            log.warn("권한 삭제 실패 - 권한을 찾을 수 없음: ({}, {})", authrtVO.getAuthrtCd(), authrtVO.getSysCd());
        }

        return result;
    }

}