package ru.soune.nocopy.service.auth;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.entity.user.UserNotActive;
import ru.soune.nocopy.repository.UserNotActiveRepository;
import ru.soune.nocopy.repository.UserRepository;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class CleanUpNotActiveUser {

    @Autowired
    private UserNotActiveRepository userNotActiveRepository;

    @Autowired
    private UserRepository userRepository;

    @Transactional
    @Scheduled(fixedDelay = 600000)
    public void cleanupNotActiveUsers() {
        LocalDateTime now = LocalDateTime.now();

        List<UserNotActive> expiredTokens = userNotActiveRepository.findByBlockedUntilBefore(now);

        for (UserNotActive userNotActive : expiredTokens) {
            User user = userNotActive.getUser();
            user.setActive(true);
            user.setFailedLoginAttempts(0);

            userRepository.save(user);
        }

        if (!expiredTokens.isEmpty()) {
            userNotActiveRepository.deleteAll(expiredTokens);

        }
    }
}