package com.kamco.cd.training.postgres.repository.members;

import com.kamco.cd.training.postgres.entity.AuthRefreshTokenEntity;
import com.kamco.cd.training.postgres.entity.QAuthRefreshTokenEntity;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.time.ZonedDateTime;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class AuthRefreshTokenImpl implements AuthRefreshTokenRepositoryCustom {

  private final JPAQueryFactory queryFactory;
  private final QAuthRefreshTokenEntity tokenEntity =
      QAuthRefreshTokenEntity.authRefreshTokenEntity;

  /**
   * subject로 조회
   *
   * @param subject 사용자 식별(UUID)
   * @return
   */
  @Override
  public Optional<AuthRefreshTokenEntity> findBySubject(String subject) {
    return Optional.ofNullable(
        queryFactory.selectFrom(tokenEntity).where(tokenEntity.subject.eq(subject)).fetchOne());
  }

  /**
   * 토큰 정보 조회
   *
   * @param subject
   * @param now
   * @return
   */
  @Override
  public Optional<AuthRefreshTokenEntity> findBySubjectAndRevokedDttmIsNullAndExpiresDttmAfter(
      String subject, ZonedDateTime now) {
    return Optional.ofNullable(
        queryFactory
            .selectFrom(tokenEntity)
            .where(
                tokenEntity.subject.eq(subject),
                tokenEntity.revokedDttm.isNull(),
                tokenEntity.expiresDttm.gt(now))
            .fetchOne());
  }
}
