import { db } from "@link-stack/bridge-common";

export interface NotifyWebhooksOptions {
  backendId: string;
  payload: any;
}

const notifyWebhooksTask = async (
  options: NotifyWebhooksOptions,
): Promise<void> => {
  const { backendId, payload } = options;

  const webhooks = await db
    .selectFrom("Webhook")
    .selectAll()
    .where("backendId", "=", backendId)
    .execute();

  for (const webhook of webhooks) {
    const { endpointUrl, httpMethod, headers } = webhook;
    const finalHeaders = { "Content-Type": "application/json", ...headers };
    console.log({ endpointUrl, httpMethod, headers, finalHeaders });
    const result = await fetch(endpointUrl, {
      method: httpMethod,
      headers: finalHeaders,
      body: JSON.stringify(payload),
    });
    console.log(result);
  }
};

export default notifyWebhooksTask;
