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

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

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

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

  console.info("Service started 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 };
};
