const messages = require('../messages');
const { phase } = require('../constants');
const { safeExec } = require('../helpers');
const { sendMessage } = require('../api');
const {
  getAdminTelegramUsers,
  getManagersTelegramUsers,
} = require('./userQuery');

// locals: { idapp, username, nomeapp, text, ... }
const notifyToTelegram = safeExec(async (ph, locals = {}) => {
  const idapp = String(locals.idapp || '');
  let text = '';

  const templ = messages.byPhase[ph] || messages.byPhase.GENERIC;
  text = templ(locals);

  // router di default: manda agli admin dell'app
  const admins = await getAdminTelegramUsers(idapp);
  for (const a of admins) {
    if (a.telegram_id) await sendMessage(a.telegram_id, text);
  }
});

const askConfirmationUser = safeExec(async (idapp, phaseCode, user) => {
  const txt = messages.askConfirmationUser({
    idapp,
    username: user?.username,
    nomeapp: user?.nomeapp,
  });
  if (user?.telegram_id) await sendMessage(user.telegram_id, txt);
});

// helper semplici
const sendNotifToAdmin = safeExec(async (idapp, title, body = '') => {
  const admins = await getAdminTelegramUsers(String(idapp));
  const txt = `📣 <b>${title}</b>\n${body}`;
  for (const a of admins) {
    if (a.telegram_id) await sendMessage(a.telegram_id, txt);
  }
});

const sendNotifToManager = safeExec(async (idapp, title, body = '') => {
  const managers = await getManagersTelegramUsers(String(idapp));
  const txt = `📣 <b>${title}</b>\n${body}`;
  for (const m of managers) {
    if (m.telegram_id) await sendMessage(m.telegram_id, txt);
  }
});

const sendNotifToAdminOrManager = safeExec(async (idapp, title, body = '', preferManagers = false) => {
  if (preferManagers) {
    return sendNotifToManager(idapp, title, body);
  }
  return sendNotifToAdmin(idapp, title, body);
});

module.exports = {
  notifyToTelegram,
  askConfirmationUser,
  sendNotifToAdmin,
  sendNotifToManager,
  sendNotifToAdminOrManager,
  phase, // re-export utile
};
