import { Repo } from "@automerge/automerge-repo";
import { BroadcastChannelNetworkAdapter } from "@automerge/automerge-repo-network-broadcastchannel";
import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb";
import { BrowserWebSocketClientAdapter } from "@automerge/automerge-repo-network-websocket";

let repo: Repo | null = null;

/** Get or create the singleton Automerge Repo instance (browser-only) */
export function getRepo(): Repo {
  if (repo) return repo;

  repo = new Repo({
    network: [
      new BrowserWebSocketClientAdapter("wss://sync.automerge.org"),
      new BroadcastChannelNetworkAdapter(),
    ],
    storage: new IndexedDBStorageAdapter("p2p-poll-app"),
  });

  return repo;
}

/** Shut down the repo and reset the singleton */
export function cleanupRepo(): void {
  if (repo) {
    repo.shutdown();
    repo = null;
  }
}
