import { type defaults as PouchDB } from "pouchdb-core";

export interface ServiceSeqTrackerDocument {
  lastSeq: string | number;
}

export type ServiceSeqTrackerDatabase =
  PouchDB.Database<ServiceSeqTrackerDocument>;

export class ServiceSeqTracker {
  /**
   * @param _id
   * @param serviceSeqTrackerDb
   * @constructor
   */
  static async Init(
    _id: string,
    serviceSeqTrackerDb: ServiceSeqTrackerDatabase,
  ) {
    const doc = await serviceSeqTrackerDb.get(_id).catch((error) => {
      if (error.name === "not_found") {
        return {
          _id,
          lastSeq: "0",
        };
      }
      throw error; // Re-throw other errors
    });
    return new ServiceSeqTracker(doc, serviceSeqTrackerDb);
  }

  private constructor(
    private doc: ServiceSeqTrackerDocument,
    private serviceSeqTrackerDb: ServiceSeqTrackerDatabase,
  ) {}

  get lastSeq() {
    return this.doc.lastSeq;
  }

  checkNextSeq(seq: number | string) {
    if (!this.doc) {
    }
    const next = parseInt(seq as string, 10);
    const current = parseInt(this.doc.lastSeq as string, 10);
    if (next < current) {
      throw new Error(
        `Sequence number is too old: ${seq} (${next} < ${current})`,
      );
    }
  }

  saveSeq(seq: number | string) {
    this.doc.lastSeq = seq;
    return this.serviceSeqTrackerDb.put(this.doc);
  }
}
