/* eslint-disable camelcase */
import { config, pgClients, getSelect } from '@opengis/fastify-table/utils.js';

import { addNotification, sendNotification } from '../../../../utils.js';

function sequence(arr, data, fn) {
  return arr.reduce((promise, row) => promise.then(() => fn({
    ...data, ...row,
  })), Promise.resolve());
}

export default async function onWidgetSet({ pg = pgClients?.client, link, user, type, payload: data = {} }) {
  const values = data.body?.match(/\B@[a-zA-z0-9а-яА-яіїІЇєЄ]+ [a-zA-z0-9а-яА-яіїІЇєЄ]+/g)
    ?.filter((el, idx, arr) => el?.replace && arr.indexOf(el) === idx)
    ?.map((el) => el.replace(/@/g, ''));

  if (type !== 'comment' || !values?.length) {
    return null;
  }

  const { sql } = await getSelect('core.user_mentioned');

  const { rows = [] } = await pg.query(`with data (id,name,email) as (${sql})
  select id, name, email from data where name = any($1)`, [values]);

  if (!rows?.length) {
    return null;
  }

  const message = `${data.body?.substring(0, 50)}...`;
  const subject = 'You were mentioned';

  await sequence(rows, {}, async ({ id, name, email }) => {
    const res = await addNotification({
      pg, user, subject, entity: data.entity_id, body: message, link, uid: id,
    });
    try {
      const res1 = await sendNotification({
        pg,
        to: email,
        // template,
        message,
        title: subject,
        data,
        nocache: 1,
      });
      if (config.local) console.info('comment notification', name, id, email, res1);
      await pg.query('update crm.notifications set sent=true where notification_id=$1', [res?.notification_id]);
    }
    catch (err) {
      console.error('comment notification send error', err.toString());
    }
  });
  console.log('comment notification add', rows);
  return null;
}
