// for example only
/*
    const res = await dataInsert({
      pg,
      table: 'crm.notifications',
      data: {
        subject: 'notif title',
        body: 'notif body',
        link: 'http://localhost:3000/api/notification',
        addressee_id: userId,
        author_id: userId,
      },
    });
*/

import { getSelectVal } from '@opengis/fastify-table/utils.js';

const maxLimit = 100;

export default async function userNotifications({
  pg, query = {}, user = {},
}) {
  const time = Date.now();

  const { uid } = user || {};

  if (!uid) {
    return { message: 'access restricted', status: 403 };
  }

  const limit = Math.min(maxLimit, +(query.limit || 5));
  const offset = query.page && query.page > 0 ? (query.page - 1) * limit : 0;

  const q = `select notification_id as id, subject, body, cdate,
  author_id, read, link, entity_id, (select avatar from admin.users where uid=a.author_id limit 1) as avatar from crm.notifications a where addressee_id=$1 order by cdate desc limit $2 offset $3`;

  if (query.sql) return q;

  const { rows = [] } = pg.pk?.['crm.notifications'] ? await pg.query(q, [uid, limit, offset]) : {};

  const values = rows.map((el) => el.author_id)
    ?.filter((el, idx, arr) => el && arr.indexOf(el) === idx);

  if (values?.length) {
    const vals = await getSelectVal({ name: 'core.user_mentioned', values });
    rows.forEach((row) => {
      Object.assign(row, { author: vals?.[row.author_id] });
    });
  }

  return { time: Date.now() - time, total: rows?.length, rows };

}
