import { tgBotUpdatesDesignDocumentsDb } from "../dbs";
import { saveUpdateString as saveUpdate } from "@hereconnect/tg-bot-update-webhook-ddoc";
import { type TgBotUpdateWebhookDesignDocument } from "@hereconnect/tg-bot-update-webhook-ddoc";

function generateTelegramSecretToken(length = 256) {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
  let token = "";
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    token += characters[randomIndex];
  }
  return token;
}

export const setupWebhookDesignDocument = async () => {
  const _id = "_design/tg_bot_webhook";

  const result: TgBotUpdateWebhookDesignDocument = {
    _id,
    type: _id,
    created_at: "",
    updated_at: "",
    updates: {
      saveUpdate,
    },
    constants: {
      telegram_secret_token: "",
    },
  };

  const { rev } = await tgBotUpdatesDesignDocumentsDb.upsert(_id, (ddoc) => {
    const isEmptyTelegramSecretToken =
      !ddoc.constants?.telegram_secret_token?.length;
    const needToSetSaveUpdateFunction =
      ddoc.updates?.saveUpdate !== result.updates.saveUpdate;

    if (!needToSetSaveUpdateFunction && !isEmptyTelegramSecretToken) {
      Object.assign(result, ddoc);
      return false;
    }

    ddoc.updated_at = new Date().toISOString();
    if (!ddoc.created_at) {
      ddoc.created_at = ddoc.updated_at;
    }

    if (isEmptyTelegramSecretToken) {
      if (!ddoc.constants) {
        ddoc.constants = result.constants;
      }
      ddoc.constants.telegram_secret_token = generateTelegramSecretToken();
    }

    if (needToSetSaveUpdateFunction) {
      if (ddoc.updates) {
        ddoc.updates.saveUpdate = result.updates.saveUpdate;
      } else {
        ddoc.updates = result.updates;
      }
    }

    return Object.assign(
      result,
      ddoc,
    ) satisfies TgBotUpdateWebhookDesignDocument;
  });

  result._rev = rev;
  return result;
};
