import { ServiceSeqTracker } from "@hereconnect/lib-service-seq-tracker";
import { CouchDBChangesStream } from "@hereconnect/couchdb-changes-stream";
import type { TgBotUpdateDocument } from "../types/TgBotUpdateDocument";
import {
  TG_BOT_UPDATES_DB_URL,
  tgBotUpdatesServiceSeqTrackerDb,
  checkDatabasesPromise,
} from "../dbs";
import { env } from "../config/env";

export const createServiceChangesTgUpdatesDb = async ({
  abortController,
}: {
  abortController: AbortController;
}) => {
  const {
    tgBotUpdatesDb: { update_seq: lastSeq },
  } = await checkDatabasesPromise;

  const serviceSeqTracker = await ServiceSeqTracker.Init(
    "_local/service:tg-bot",
    tgBotUpdatesServiceSeqTrackerDb,
  );

  const changesStream = new CouchDBChangesStream<TgBotUpdateDocument>(
    TG_BOT_UPDATES_DB_URL,
    {
      abortController,
      since: serviceSeqTracker.lastSeq,
      feed: "continuous",
      include_docs: true,
      heartbeat: env.HEARTBEAT_INTERVAL,
      filter: "_selector",
      selector: {
        type: "tg_bot_update",
      } satisfies Partial<TgBotUpdateDocument>,
    },
  );

  console.info(
    "Service started listening changes tg_bot_update from sequence",
    serviceSeqTracker.lastSeq,
  );

  if (
    parseInt(serviceSeqTracker.lastSeq.toString(), 10) ===
    parseInt(lastSeq.toString(), 10)
  ) {
    console.log("Since is the last seq");
  } else {
    console.log("Last seq is", lastSeq);
  }

  return { changesStream, serviceSeqTracker };
};
