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

import com.kamco.cd.kamcoback.auth.BCryptSaltGenerator;
import com.kamco.cd.kamcoback.common.exception.CustomApiException;
import com.kamco.cd.kamcoback.members.dto.MembersDto;
import com.kamco.cd.kamcoback.members.dto.MembersDto.Basic;
import com.kamco.cd.kamcoback.postgres.core.MembersCoreService;
import java.util.UUID;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

  private final MembersCoreService membersCoreService;

  /**
   * 회원목록 조회
   *
   * @param searchReq
   * @return
   */
  public Page<Basic> findByMembers(MembersDto.SearchReq searchReq) {
    return membersCoreService.findByMembers(searchReq);
  }

  /**
   * 회원정보 수정
   *
   * @param uuid
   * @param updateReq
   */
  public void updateMember(UUID uuid, MembersDto.UpdateReq updateReq) {

    if (StringUtils.isNotBlank(updateReq.getPassword())) {

      if (!this.isValidPassword(updateReq.getPassword())) {
        throw new CustomApiException("WRONG_PASSWORD", HttpStatus.BAD_REQUEST);
      }

      if (StringUtils.isBlank(updateReq.getEmployeeNo())) {
        throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST);
      }

      // salt 생성, 사번이 salt
      String salt =
          BCryptSaltGenerator.generateSaltWithEmployeeNo(updateReq.getEmployeeNo().trim());

      // 패스워드 암호화, 초기 패스워드 고정
      String hashedPassword = BCrypt.hashpw(updateReq.getPassword(), salt);
      updateReq.setPassword(hashedPassword);
    }

    membersCoreService.updateMembers(uuid, updateReq);
  }

  /**
   * 대문자 1개 이상 소문자 1개 이상 숫자 1개 이상 특수문자(!@#$) 1개 이상
   *
   * @param password
   * @return
   */
  private boolean isValidPassword(String password) {
    String regex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[!@#$]).{8,20}$";
    return Pattern.matches(regex, password);
  }
}
