package ru.soune.nocopy.service.register;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.user.EmailVerificationToken;
import ru.soune.nocopy.repository.EmailVerificationTokenRepository;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class CleanUpVerifyTokens {

    private final EmailVerificationTokenRepository emailVerificationTokenRepository;

    @Transactional
    @Scheduled(fixedDelay = 30000)
    public void cleanupExpiredTokens() {
        LocalDateTime now = LocalDateTime.now();
        log.info("Check time for tokens");
        List<EmailVerificationToken> expiredTokens = emailVerificationTokenRepository.findByExpiresAtBefore(now);

        if (!expiredTokens.isEmpty()) {
            emailVerificationTokenRepository.deleteAll(expiredTokens);
        }
    }
}
