import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { dirname } from "path";
import { ReconciliationCursor, ReconciliationStore } from "../types";
import { IReconciliationCursorStore } from "./StateStoreContracts";

export class ReconciliationStoreService implements IReconciliationCursorStore {
  constructor(private filePath: string) {
    this.ensureStore();
  }

  async getCursor(chainType: string): Promise<ReconciliationCursor | null> {
    const store = this.readStore();
    return store.cursors[chainType] || null;
  }

  async upsertCursor(chainType: string, fromBlock: string): Promise<void> {
    const store = this.readStore();
    store.cursors[chainType] = {
      chain_type: chainType,
      from_block: fromBlock,
      updated_at: new Date().toISOString(),
    };
    this.writeStore(store);
  }

  private ensureStore(): void {
    if (!existsSync(dirname(this.filePath))) {
      mkdirSync(dirname(this.filePath), { recursive: true });
    }

    if (!existsSync(this.filePath)) {
      this.writeStore({ version: 1, cursors: {} });
    }
  }

  private readStore(): ReconciliationStore {
    const store = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<ReconciliationStore>;
    return {
      version: 1,
      cursors: store.cursors || {},
    };
  }

  private writeStore(store: ReconciliationStore): void {
    writeFileSync(this.filePath, JSON.stringify(store, null, 2), "utf8");
  }
}
