const cron = require('node-cron');
const tools = require('../tools/general');

async function mycron() {
  try {
    const sendemail = require('../sendemail');
    const { Cron } = require('../models/cron');
    const arr = await tools.getApps();

    for (const app of arr) {
      await sendemail.checkifPendingNewsletter(app.idapp);
      await sendemail.checkifSentNewsletter(app.idapp);
      await Cron.startJobCron(app.idapp);
    }
  } catch (e) {
    console.error('Err mycron:', e);
  }
}

async function mycron_30min() {
  const { Settings } = require('../models/settings');
  const arr = await tools.getApps();

  for (const app of arr) {
    const enabled = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false);
    if (enabled) {
      // aggiungi qui logiche aggiuntive
    }
  }
}

async function mycron_everyday() {
  const { User } = require('../models/user');
  const telegrambot = require('../telegram/telegrambot');

  try {
    const arrapps = await tools.getApps();
    for (const app of arrapps) {
      const usersblocked = await User.find({
        idapp: app.idapp,
        retry_pwd: { $exists: true, $gte: 29 },
      }).lean();

      for (const user of usersblocked) {
        await User.findByIdAndUpdate(user._id, { $set: { retry_pwd: 20 } });
        const text = `⚠️ L'utente ${user.username} (${user.name} ${user.surname}) è stato sbloccato!`;
        await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
      }
    }
  } catch (e) {
    console.error('mycron_everyday:', e);
  }
}

// ⏱️ pianifica i cron
function setupCronJobs() {
  cron.schedule('*/1 * * * *', mycron);
  cron.schedule('*/60 * * * *', mycron_30min);
  cron.schedule('0 21 * * *', mycron_everyday);
  console.log('⏱️ Cron Jobs attivi');
}

module.exports = { mycron, mycron_30min, mycron_everyday, setupCronJobs };
