const tools = require('../tools/general');
const { Newstosent } = require('../models/newstosent');

async function resetProcessingJob() {
  try {
    const records = await Newstosent.find({});
    for (const rec of records) {
      rec.processing_job = false;
      await Newstosent.findByIdAndUpdate(rec._id, { $set: rec }, { new: false });
    }
    console.log('✅ resetProcessingJob completato');
  } catch (err) {
    console.error('❌ Errore resetProcessingJob:', err.message);
  }
}

async function testmsgwebpush() {
  try {
    const { User } = require('../models/user');

    const users = await User.find({ username: 'surya1977', idapp: '1' }).lean();
    for (const user of users) {
      await tools.sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', []);
    }
    console.log('✅ testmsgwebpush completato');
  } catch (err) {
    console.error('❌ Errore testmsgwebpush:', err.message);
  }
}

async function populateDBadmin() {
  const { CfgServer } = require('../models/cfgserver');
  const { ObjectId } = require('mongodb');

  try {
    const cfg = new CfgServer({
      _id: new ObjectId(),
      idapp: '9',
      chiave: 'vers',
      userId: 'ALL',
      valore: '0.1.2',
    });
    await cfg.save();
    console.log('✅ populateDBadmin completato');
  } catch (err) {
    console.error('❌ Errore populateDBadmin:', err.message);
  }
}

async function inizia() {
  try {
    telegrambot = require('../telegram/telegrambot');
    if (false) {
      const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
      const outputPath = './comuni_italia_geojson.json';
      downloadGeoJSON(url, outputPath);
    }

    mycron_everyday();

    if (process.env.NODE_ENV === 'development') {
      await telegrambot.sendMsgTelegram(
        tools.FREEPLANET,
        shared_consts.ADMIN_USER_SERVER,
        `Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`
      );

      await telegrambot.sendMsgTelegramByIdTelegram(
        tools.FREEPLANET,
        telegrambot.ADMIN_IDTELEGRAM_SERVER,
        `Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `🔅 Il Server ${process.env.DATABASE} è appena ripartito!`
      );
    } else {
      await telegrambot.sendMsgTelegramToTheAdminAllSites(
        `Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`,
        false
      );
    }

    await Site.createFirstUserAdmin();

    /*const {Circuit} = require('./models/circuit');
    
        await Circuit.setDeperimentoOff();
    
         */
  } catch (e) {}
}

module.exports = {
  resetProcessingJob,
  testmsgwebpush,
  populateDBadmin,
  inizia,
};
