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

import incheon.ags.ias.user.mapper.UserMapper;
import incheon.ags.ias.user.service.UserService;
import incheon.ags.ias.user.vo.UserSearchVO;
import incheon.ags.ias.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * 사용자 관리 Service 구현체
 */
@Service("userService")
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends EgovAbstractServiceImpl implements UserService {
    private final UserMapper userMapper;

    /* ========================================
     * 사용자 관련 메서드
     * ======================================== */

    @Override
    public List<Map<String, Object>> selectUserList(UserSearchVO userSearchVO) throws Exception {
        log.debug("사용자 목록 조회 - 검색조건: {}", userSearchVO);
        return userMapper.selectUserList(userSearchVO);
    }

    @Override
    public int selectUserCnt(UserSearchVO userSearchVO) throws Exception {
        log.debug("사용자 총 개수 조회 - 검색조건: {}", userSearchVO);
        return userMapper.selectUserCnt(userSearchVO);
    }

    @Override
    public UserVO selectUserDetail(UserVO userVO) throws Exception {
        log.debug("사용자 상세 조회 - userId: {}", userVO.getUserId());
        return userMapper.selectUserDetail(userVO);
    }

    @Override
    public int insertUser(UserVO userVO) throws Exception {
        log.info("사용자 등록 - userId: {}, userNm: {}", userVO.getUserId(), userVO.getUserNm());
        
        // 필수 필드 검증
        validateUserForInsert(userVO);
        
        return userMapper.insertUser(userVO);
    }

    @Override
    public int updateUser(UserVO userVO) throws Exception {
        log.info("사용자 수정 - userId: {}, userNm: {}", userVO.getUserId(), userVO.getUserNm());
        
        // 필수 필드 검증
        validateUserForUpdate(userVO);
        
        return userMapper.updateUser(userVO);
    }

    @Override
    public int deleteUser(UserVO userVO) throws Exception {
        log.info("사용자 삭제 - userId: {}", userVO.getUserId());
        
        if (!StringUtils.hasText(userVO.getUserId())) {
            throw new IllegalArgumentException("사용자 ID는 필수입니다.");
        }
        
        return userMapper.deleteUser(userVO);
    }

    /* ========================================
     * 부서/직급 관련 메서드
     * ======================================== */

    @Override
    public List<Map<String, Object>> deptList() throws Exception {
        log.debug("부서 목록 조회");
        return userMapper.deptList();
    }

    @Override
    public List<Map<String, Object>> jbgdList() throws Exception {
        log.debug("직급 목록 조회");
        return userMapper.jbgdList();
    }

    @Override
    public Map<String, Object> selectUserStatusCnt() throws Exception {
        log.debug("사용자 상태별 개수 조회");
        return userMapper.selectUserStatusCnt();
    }

    @Override
    public List<Map<String, Object>> selectUserCntByDept() throws Exception {
        log.debug("부서별 사용자 수 조회");
        return userMapper.selectUserCntByDept();
    }

    @Override
    public boolean isUserIdDuplicate(String userId) throws Exception {
        log.debug("사용자 ID 중복 체크 - userId: {}", userId);
        
        if (!StringUtils.hasText(userId)) {
            return false;
        }
        
        UserVO searchVO = new UserVO();
        searchVO.setUserId(userId);
        UserVO existingUser = userMapper.selectUserDetail(searchVO);
        
        return existingUser != null;
    }

    @Override
    public boolean isEmailDuplicate(String emlAddr) throws Exception {
        log.debug("이메일 중복 체크 - emlAddr: {}", emlAddr);
        
        if (!StringUtils.hasText(emlAddr)) {
            return false;
        }
        
        // TODO: 이메일 중복 체크 쿼리 구현 필요
        // 현재는 기본 구현만 제공
        return false;
    }

    /* ========================================
     * Private 메서드
     * ======================================== */

    /**
     * 사용자 등록 시 필수 필드 검증
     */
    private void validateUserForInsert(UserVO userVO) {
        if (!StringUtils.hasText(userVO.getUserId())) {
            throw new IllegalArgumentException("사용자 ID는 필수입니다.");
        }
        if (!StringUtils.hasText(userVO.getUserNm())) {
            throw new IllegalArgumentException("사용자명은 필수입니다.");
        }
        if (!StringUtils.hasText(userVO.getEmlAddr())) {
            throw new IllegalArgumentException("이메일 주소는 필수입니다.");
        }
    }

    /**
     * 사용자 수정 시 필수 필드 검증
     */
    private void validateUserForUpdate(UserVO userVO) {
        if (!StringUtils.hasText(userVO.getUserId())) {
            throw new IllegalArgumentException("사용자 ID는 필수입니다.");
        }
        if (!StringUtils.hasText(userVO.getUserNm())) {
            throw new IllegalArgumentException("사용자명은 필수입니다.");
        }
        if (!StringUtils.hasText(userVO.getEmlAddr())) {
            throw new IllegalArgumentException("이메일 주소는 필수입니다.");
        }
    }
}
