package com.dbnt.kcscbackend.admin.users.service;

import com.dbnt.kcscbackend.admin.users.mapper.AdminUsersMapper;
import com.dbnt.kcscbackend.auth.entity.UserInfo;
import com.dbnt.kcscbackend.auth.repository.UserInfoRepository;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AdminUsersService extends EgovAbstractServiceImpl {

  private final UserInfoRepository userInfoRepository;
  private final AdminUsersMapper usersMapper;

  public List<UserInfo> selectUserList(UserInfo params) {
    return usersMapper.selectUserList(params);
  }

  public Integer selectUserListCnt(UserInfo params) {
    return usersMapper.selectUserListCnt(params);
  }

  public UserInfo selectUserInfo(Integer userSeq) {
    UserInfo info = userInfoRepository.findById(userSeq).orElse(new UserInfo());
    info.setPassword(null);
    return info;
  }

  @Transactional
  public Integer updateUserInfo(UserInfo info, String updateUser) {
    UserInfo savedInfo = userInfoRepository.findById(info.getUserSeq()).orElse(null);
    UserInfo emailChk = userInfoRepository.findByEmail(info.getEmail()).orElse(null);
    if(savedInfo==null){
      return -1;
    }else if(emailChk != null){
      if(!emailChk.getUserSeq().equals(info.getUserSeq())){
        return -2;
      }
    }

    savedInfo.setUserNm(info.getUserNm());
    if(!info.getPassword().isEmpty()){
      savedInfo.setPassword(info.convertPassword(info.getPassword()));
    }
    savedInfo.setEmail(info.getEmail());
    savedInfo.setPhoneNum(info.getPhoneNum());
    savedInfo.setUserRole(info.getUserRole());
    savedInfo.setStatus(info.getStatus());
    savedInfo.setLastChgId(updateUser);
    savedInfo.setLastChgDt(LocalDateTime.now());

    return savedInfo.getUserSeq();
  }

  @Transactional
  public void deleteUserInfo(Integer userSeq) {
    userInfoRepository.deleteById(userSeq);
  }

}
