content: package com.alkl1m.taskmanager.service.auth;
  
  import com.alkl1m.taskmanager.entity.RefreshToken;
  import com.alkl1m.taskmanager.controller.exception.TokenRefreshException;
  import com.alkl1m.taskmanager.repository.RefreshTokenRepository;
  import com.alkl1m.taskmanager.repository.UserRepository;
  import lombok.Getter;
  import lombok.Setter;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Value;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
  
  import java.time.Instant;
  import java.util.Optional;
  import java.util.UUID;
  
  @Service
  public class RefreshTokenService {
      @Setter
      @Getter
      @Value("${application.security.jwt.refreshExpirationMs}")
      private Long refreshTokenDurationMs;
      @Autowired
      private RefreshTokenRepository refreshTokenRepository;
      @Autowired
      private UserRepository userRepository;
  
      public Optional<RefreshToken> findByToken(String token) {
          return refreshTokenRepository.findByToken(token);
      }
  
      public RefreshToken createRefreshToken(Long userId) {
          RefreshToken refreshToken = new RefreshToken();
  
          refreshToken.setUser(userRepository.findById(userId).get());
          refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
          refreshToken.setToken(UUID.randomUUID().toString());
  
          refreshToken = refreshTokenRepository.save(refreshToken);
          return refreshToken;
      }
  
      public RefreshToken verifyExpiration(RefreshToken token) {
          if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
              refreshTokenRepository.delete(token);
              throw new TokenRefreshException(token.getToken(), "Refresh token was expired");
          }
          return token;
      }
  
      @Transactional
      public void deleteByUserId(Long userId) {
          refreshTokenRepository.deleteByUser(userRepository.findById(userId).get());
      }
  }
  