/* eslint-disable camelcase */
import logger from "../logger";
import { IncomingMessagev1 } from "@digiresilience/node-signald/build/main/generated";
import { withDb, AppDatabase } from "../db";
import workerUtils from "../utils";

interface WebhookPayload {
  to: string;
  from: string;
  message_id: string;
  sent_at: string;
  message: string;
  attachment: string | null;
  filename: string | null;
  mime_type: string | null;
}

interface SignaldMessageTaskOptions {
  message: IncomingMessagev1;
  botId: string;
  botPhoneNumber: string;
  attachment: string;
  filename: string;
  mimetype: string;
}

const formatPayload = (opts: SignaldMessageTaskOptions): WebhookPayload => {
  const { botId, botPhoneNumber, message, attachment, filename, mimetype } = opts;
  const { source, timestamp, data_message: dataMessage } = message;

  const { number }: any = source;

  const { body, attachments }: any = dataMessage;

  return {
    to: botPhoneNumber,
    from: number,
    message_id: `${botId}-${timestamp}`,
    sent_at: `${timestamp}`,
    message: body,
    attachment,
    filename,
    mime_type: mimetype,
  };
};

const notifyWebhooks = async (
  db: AppDatabase,
  messageInfo: SignaldMessageTaskOptions
) => {
  const {
    botId,
    message: { timestamp },
  } = messageInfo;
  const webhooks = await db.webhooks.findAllByBackendId("signal", botId);
  if (webhooks && webhooks.length === 0) {
    logger.debug({ botId }, "no webhooks registered for signal bot");
    return;
  }

  webhooks.forEach(({ id }) => {
    const payload = formatPayload(messageInfo);
    logger.debug(
      { payload },
      "formatted signal bot payload for notify-webhook"
    );
    workerUtils.addJob(
      "notify-webhook",
      {
        payload,
        webhookId: id,
      },
      {
        // this de-deduplicates the job
        jobKey: `webhook-${id}-message-${botId}-${timestamp}`,
      }
    );
  });
};

const signaldMessageTask = async (
  options: SignaldMessageTaskOptions
): Promise<void> => {
  console.log(options);
  withDb(async (db: AppDatabase) => {
    await notifyWebhooks(db, options);
  });
};

export default signaldMessageTask;
