const { sendMessage } = require('../api');
const { safeExec, eachSeries } = require('../helpers');
const tools = require('../../tools/general');
const {
  getAdminTelegramUsers,
  getManagersTelegramUsers,
  getAllTelegramUsersByApp,
} = require('./userQuery');

const sendMsgTelegramToTheAdminAllSites = safeExec(async (text, alsoGroups = false) => {
  const apps = await tools.getApps(); // deve restituire {idapp,...}
  await eachSeries(apps, async (app) => {
    const admins = await getAdminTelegramUsers(app.idapp);
    await eachSeries(admins, async (u) => sendMessage(u.telegram_id, text));
    if (alsoGroups && app?.telegram_admin_group_id) {
      await sendMessage(app.telegram_admin_group_id, text);
    }
  });
});

const sendMsgTelegramByIdApp = safeExec(async (idapp, text) => {
  const users = await getAllTelegramUsersByApp(idapp);
  await eachSeries(users, async (u) => sendMessage(u.telegram_id, text));
});

const sendMsgTelegramToTheManagers = safeExec(async (idapp, text) => {
  const managers = await getManagersTelegramUsers(idapp);
  await eachSeries(managers, async (u) => sendMessage(u.telegram_id, text));
});

const sendMsgTelegramToTheAdmin = safeExec(async (idapp, text) => {
  const admins = await getAdminTelegramUsers(idapp);
  await eachSeries(admins, async (u) => sendMessage(u.telegram_id, text));
});

const sendMsgTelegramToTheGroup = safeExec(async (chatId, text) => {
  if (!chatId) return null;
  return sendMessage(chatId, text);
});

module.exports = {
  sendMsgTelegramToTheAdminAllSites,
  sendMsgTelegramByIdApp,
  sendMsgTelegramToTheManagers,
  sendMsgTelegramToTheAdmin,
  sendMsgTelegramToTheGroup,
};
