package com.codenetworkz.portfoliowebsite.crons;

import com.codenetworkz.portfoliowebsite.exceptions.InternalServerException;
import com.codenetworkz.portfoliowebsite.models.ContactForm;
import com.codenetworkz.portfoliowebsite.models.Status;
import com.codenetworkz.portfoliowebsite.repositories.ContactFormRepository;
import com.codenetworkz.portfoliowebsite.services.EmailSendService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class MailSenderCron {

    private final ContactFormRepository contactFormRepository;
    private final EmailSendService emailSendService;

    @Value("${spring.mail.username}")
    private String recipientEmail;

    @Value("${message.contractus.subject}")
    private String subject;

    public MailSenderCron(ContactFormRepository contactFormRepository, EmailSendService emailSendService) {
        this.contactFormRepository = contactFormRepository;
        this.emailSendService= emailSendService;
    }

// ┌───────────── 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/2 * *")
 //   @Scheduled(cron = "0 */2 * * * *")
    public void sendPendingMessageEmail() throws InternalServerException{
        LocalDate last2Day = LocalDate.now().minusDays(2);
        List<ContactForm> sendMails = contactFormRepository.findAllBySendMessageAndCreateAtIsBefore(Status.No, last2Day);
        try {
            sendMails.forEach(sendMail -> {
                sendMail.setSendMessage(Status.No);
                emailSendService.sendEmail(sendMail.getEmail(), subject, sendMail.getMessage(), recipientEmail);
                contactFormRepository.save(sendMail);});
        }catch (Exception e){
            throw new InternalServerException("There is problem with database, please try after same time.");
        }
    }
}
