package com.kamco.cd.kamcoback.auth.service;

import com.kamco.cd.kamcoback.auth.dto.AuthDto;
import com.kamco.cd.kamcoback.auth.dto.AuthDto.Basic;
import com.kamco.cd.kamcoback.postgres.core.AuthCoreService;
import com.kamco.cd.kamcoback.postgres.entity.UserEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class AuthService {

  private final AuthCoreService authCoreService;
  private final PasswordEncoder passwordEncoder;

  /**
   * 관리자 등록
   *
   * @param saveReq
   * @return
   */
  @Transactional
  public UserEntity save(AuthDto.SaveReq saveReq) {
    saveReq.setUserPw(passwordEncoder.encode(saveReq.getUserPw()));
    return authCoreService.save(saveReq);
  }

  /**
   * 관리자 정보 수정
   *
   * @param id
   * @param saveReq
   * @return
   */
  public UserEntity update(Long id, AuthDto.SaveReq saveReq) {
    if (saveReq.getUserPw() != null) {
      saveReq.setUserPw(passwordEncoder.encode(saveReq.getUserPw()));
    }
    return authCoreService.update(id, saveReq);
  }

  /**
   * 관리자 삭제
   *
   * @param id
   * @return
   */
  public UserEntity withdrawal(Long id) {
    return authCoreService.withdrawal(id);
  }

  /**
   * 시퀀스 id로 관리자 조회
   *
   * @param id
   * @return
   */
  public AuthDto.Basic getFindUserById(Long id) {
    return authCoreService.findUserById(id);
  }

  /**
   * 관리자 목록 조회
   *
   * @param searchReq
   * @return
   */
  public Page<Basic> getUserList(AuthDto.SearchReq searchReq) {
    return authCoreService.getUserList(searchReq);
  }
}
