package com.codenetworkz.blog.crons;

import com.codenetworkz.blog.exceptions.InternalServerException;
import com.codenetworkz.blog.exceptions.UserNotFoundException;
import com.codenetworkz.blog.models.Status;
import com.codenetworkz.blog.models.User;
import com.codenetworkz.blog.repositories.UserRepository;
import com.codenetworkz.blog.services.impl.UserServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class DeleteDeactivateUser extends UserServiceImpl {

    private final UserRepository userRepository;


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

// ┌───────────── second (0-59)
// │ ┌───────────── minute (0 - 59)
// │ │ ┌───────────── hour (0 - 23)
// │ │ │ ┌───────────── day of the month (1 - 31)
// │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
// │ │ │ │ │ ┌───────────── day of the week (0 - 7)
// │ │ │ │ │ │          (0 or 7 is Sunday, or MON-SUN)
// │ │ │ │ │ │
// * * * * * *

   //ervery 30 days cron run in backgraond
   // @Scheduled(cron = "0 0 0 1/30 * *")
    public void delete() throws InternalServerException, UserNotFoundException {
        LocalDate today = LocalDate.now();
        LocalDateTime last30Day = LocalDateTime.now().minusDays(30);
        List<User> deletedUsers = userRepository.findAllByIsActiveAndIsDeleteAndDeleteAtIsBefore("N", null, last30Day);
        try {
            deletedUsers.forEach(user -> { user.setIsDelete(Status.YES); userRepository.save(user);});
        }catch (Exception e){
            throw new InternalServerException("There is problem with database, please try after same time.");
        }
    }

}