import { setupWebhookDesignDocument } from "./setupWebhookDesignDocument";
import { TG_BOT_UPDATES_DB_NAME, tgBotUpdatesDesignDocumentsDb } from "../dbs";
import { env } from "../config/env";
import { Bot } from "grammy";
import { MyContext } from "../types/myContext";

export const setupWebHook = async (bot: Bot<MyContext>) => {
  const designDocument = await setupWebhookDesignDocument();
  const update: keyof typeof designDocument.updates = "saveUpdate";
  const webhookUrl = `${env.PUBLIC_API_URL}/${TG_BOT_UPDATES_DB_NAME}/${designDocument._id}/_update/${update}`;
  if (designDocument.constants.telegram_webhook_url !== webhookUrl) {
    await bot.api.setWebhook(webhookUrl, {
      secret_token: designDocument.constants.telegram_secret_token,
    });
    designDocument.constants.telegram_webhook_url = webhookUrl;
    const { rev } = await tgBotUpdatesDesignDocumentsDb.put(designDocument);
    designDocument._rev = rev;
  }
  return designDocument;
};
