const tools = require('../tools/general');
const Site = require('../models/site');

async function faitest() {
  const telegrambot = require('../telegram/telegrambot');
  // console.log('Fai Test:')

  const testfind = false;

  // const $vers = tools.getVersionint('1.92.45');

  if (true) {
    // tools.execScript("ls -la");
  }

  if (false) {
    prova = tools.removeAtChar('@prova');
  }

  if (false) {
    const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin);
    console.log('prova', prova);
  }

  if (testfind) {
    const { City } = require('../models/city');

    let miacity = 'roma';
    const ris = await City.findByCity(miacity);

    console.log('ris', ris);
  }

  const { User } = require('../models/user');

  if (false) {
    let myuser = await User.findOne({
      idapp: '1',
      username: 'paoloar77',
    });
    const langdest = 'it';

    telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
  }

  const inviaemailtestsurya = false;

  if (inviaemailtestsurya) {
    const user = await User.findOne({
      idapp: 13,
      username: 'surya2',
    });

    const sendemail = require('../sendemail');

    await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, '13', '');
  }

  if (false) {
    const { User } = require('../models/user');

    const idapp = tools.FREEPLANET;
    const idreg = 0;

    try {
      const user = await User.findOne({
        idapp,
        username: 'paoloar773',
      });

      user.aportador_solidario = 'surya1977';

      let mylocalsconf = {
        idapp,
        dataemail: null,
        locale: user.lang,
        nomeapp: tools.getNomeAppByIdApp(idapp),
        strlinksito: tools.getHostByIdApp(idapp),
        strlinkreg: '',
        username: user.username,
        name: user.name,
        surname: user.surname,
        forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
        emailto: '',
        user,
      };

      await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
    } catch (e) {
      console.log('error ' + e);
    }
  }
}

async function runStartupTasks() {
  //mystart
  try {
    // 1) log versione + elenco app
    const vers = await tools.getVersServer();
    const apps = await tools.getApps();
    console.log('----------------------------------------------');
    console.log(`🌍 Versione Server: ${vers}`);
    console.log('📱 App caricate:');
    for (const app of apps) {
      console.log(`   • ID: ${app.idapp} → ${app.nomeapp || app.name || 'N/A'}`);
    }
    console.log('----------------------------------------------');

    const telegrambot = require('../telegram/telegrambot');

    const { resetProcessingJob, testmsgwebpush, inizia } = require('./extraJobs');

    // 2) azioni post-boot
    await Site.createFirstUserAdmin?.();

    // 3) test notifiche webpush (facoltativo: metti dietro un flag)
    if (process.env.ENABLE_TEST_WEBPUSH === 'true') {
      await testmsgwebpush();
    }

    await inizia();

    if (true) {
      // const Seed = require('../scripts/seedTemplates');
    }

    // 4) reset job pendenti
    await resetProcessingJob();

    // 5) popolamenti/attività extra (facoltativo)
    const populate = require('../populate/populate');
    populate.popolaTabelleNuove();

    faitest();

    // 6) ping agli admin
    await telegrambot.sendMsgTelegramToTheAdminAllSites(`🔅 Server ${vers} avviato con successo`);
  } catch (err) {
    console.error('❌ errore in runStartupTasks:', err.message);
  }
}

module.exports = { runStartupTasks };
