/* eslint-disable camelcase */
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;
  filename: string;
  mime_type: string;
}

interface WhatsappMessageTaskOptions {
  waMessageId: string;
  waMessage: string;
  waTimestamp: string;
  attachment: string;
  filename: string;
  mimetype: string;
  botPhoneNumber: string;
  whatsappBotId: string;
}

const formatPayload = (
  messageInfo: WhatsappMessageTaskOptions
): WebhookPayload => {
  const {
    waMessageId,
    waMessage,
    waTimestamp,
    attachment,
    filename,
    mimetype,
    botPhoneNumber,
  } = messageInfo;
  const parsedMessage = JSON.parse(waMessage);
  const message = parsedMessage.message?.conversation ?? 
    parsedMessage.message?.extendedTextMessage?.text ?? 
    parsedMessage.message?.imageMessage?.caption ??
    parsedMessage.message?.videoMessage?.caption;

  return {
    to: botPhoneNumber,
    from: parsedMessage.key.remoteJid,
    message_id: waMessageId,
    sent_at: waTimestamp,
    message,
    attachment,
    filename,
    mime_type: mimetype,
  };
};

const notifyWebhooks = async (
  db: AppDatabase,
  messageInfo: WhatsappMessageTaskOptions
) => {
  const { waMessageId, whatsappBotId } = messageInfo;
  const webhooks = await db.webhooks.findAllByBackendId(
    "whatsapp",
    whatsappBotId
  );
  if (webhooks && webhooks.length === 0) return;

  webhooks.forEach(({ id }) => {
    const payload = formatPayload(messageInfo);
    console.log({ payload });
    workerUtils.addJob(
      "notify-webhook",
      {
        payload,
        webhookId: id,
      },
      {
        // this de-deduplicates the job
        jobKey: `webhook-${id}-message-${waMessageId}`,
      }
    );
  });
};

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

export default whatsappMessageTask;
