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

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.regex.Pattern;
import lombok.RequiredArgsConstructor;
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 id
   * @param initReq
   */
  @Transactional
  public void resetPassword(String id, MembersDto.InitReq initReq) {

    if (!isValidPassword(initReq.getPassword())) {
      throw new CustomApiException("WRONG_PASSWORD", HttpStatus.BAD_REQUEST);
    }
    membersCoreService.resetPassword(id, initReq);
  }

  /**
   * 대문자 1개 이상 소문자 1개 이상 숫자 1개 이상 특수문자(!@#$) 1개 이상
   *
   * @param password
   * @return
   */
  private boolean isValidPassword(String password) {
    String passwordPattern =
      "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[!@#$%^&*()_+\\-\\[\\]{};':\"\\\\|,.<>/?]).{8,20}$";
    return Pattern.matches(passwordPattern, password);
  }
}
