package com.kamco.cd.kamcoback.postgres.core;

import com.kamco.cd.kamcoback.auth.dto.AuthDto;
import com.kamco.cd.kamcoback.auth.dto.AuthDto.SaveReq;
import com.kamco.cd.kamcoback.postgres.entity.UserEntity;
import com.kamco.cd.kamcoback.postgres.repository.auth.AuthRepository;
import jakarta.persistence.EntityNotFoundException;
import java.time.ZonedDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthCoreService {

  private final AuthRepository authRepository;

  /**
   * 관리자 등록
   *
   * @param saveReq
   * @return
   */
  public UserEntity save(SaveReq saveReq) {
    if (authRepository.findByUserId(saveReq.getUserId()).isPresent()) {
      new EntityNotFoundException("중복된 아이디가 있습니다. " + saveReq.getUserId());
    }

    UserEntity userEntity =
        new UserEntity(
            null,
            saveReq.getUserAuth(),
            saveReq.getUserNm(),
            saveReq.getUserId(),
            saveReq.getEmpId(),
            saveReq.getUserEmail(),
            saveReq.getUserPw());

    return authRepository.save(userEntity);
  }

  /**
   * 관리자 정보 수정
   *
   * @param id
   * @param saveReq
   * @return
   */
  public UserEntity update(Long id, AuthDto.SaveReq saveReq) {
    UserEntity userEntity =
        authRepository.findById(id).orElseThrow(() -> new RuntimeException("유저가 존재하지 않습니다."));

    if (saveReq.getUserAuth() != null) {
      userEntity.setUserAuth(saveReq.getUserAuth());
    }

    if (saveReq.getUserNm() != null) {
      userEntity.setUserNm(saveReq.getUserNm());
    }

    if (saveReq.getUserId() != null) {
      userEntity.setUserId(saveReq.getUserId());
    }

    if (saveReq.getEmpId() != null) {
      userEntity.setEmpId(saveReq.getEmpId());
    }

    if (saveReq.getUserEmail() != null) {
      userEntity.setUserEmail(saveReq.getUserEmail());
    }

    if (saveReq.getUserPw() != null) {
      userEntity.setUserPw(saveReq.getUserPw());
    }

    return authRepository.save(userEntity);
  }

  /**
   * 관리자 삭제
   *
   * @param id
   * @return
   */
  public UserEntity withdrawal(Long id) {
    UserEntity userEntity =
        authRepository.findById(id).orElseThrow(() -> new RuntimeException("유저가 존재하지 않습니다."));

    userEntity.setId(id);
    userEntity.setDateWithdrawal(ZonedDateTime.now());
    userEntity.setState("WITHDRAWAL");

    return authRepository.save(userEntity);
  }

  /**
   * 시퀀스 id로 관리자 조회
   *
   * @param id
   * @return
   */
  public AuthDto.Basic findUserById(Long id) {
    UserEntity entity =
        authRepository
            .findUserById(id)
            .orElseThrow(() -> new EntityNotFoundException("관리자를 찾을 수 없습니다. " + id));
    return entity.toDto();
  }

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