package ru.ulstu.user.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.user.model.User;
import ru.ulstu.user.repository.UserRepository;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class UserScheduler {
    private final Logger log = LoggerFactory.getLogger(UserScheduler.class);

    private final UserRepository userRepository;

    public UserScheduler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void removeNotActivatedUsers() {
        log.debug("UserScheduler.removeNotActivatedUsers started");
        List<User> users = userRepository.findAllByActivatedIsFalseAndActivationDateBefore(
                DateUtils.instantToDate(Instant.now().minus(3, ChronoUnit.DAYS)));
        users.forEach(user -> {
            log.debug("Deleting not activated user {}", user.getLogin());
            userRepository.delete(user);
        });
        log.debug("UserScheduler.removeNotActivatedUsers finished");
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void removeUnusedRestKeyRequestsOfUsers() {
        log.debug("UserScheduler.removeUnusedRestKeyRequestsOfUsers started");
        List<User> users = userRepository.findAllByResetKeyNotNullAndResetDateBefore(
                DateUtils.instantToDate(Instant.now().minus(7, ChronoUnit.DAYS)));
        users.forEach(user -> {
            log.debug("Deleting old reset key request of user {}", user.getLogin());
            user.setResetKey(null);
            user.setResetDate(null);
            userRepository.save(user);
        });
        log.debug("UserScheduler.removeUnusedRestKeyRequestsOfUsers finished");
    }
}
