import { useSyncExternalStore } from "react";

export type ContentScope = "documents" | "attachments";

const revisions: Record<ContentScope, number> = {
  documents: 0,
  attachments: 0,
};
const listeners = new Set<() => void>();

export function notifyContentChanged(...scopes: ContentScope[]): void {
  for (const scope of new Set(scopes)) revisions[scope] += 1;
  for (const listener of listeners) listener();
}

export function getContentRevision(scope: ContentScope): number {
  return revisions[scope];
}

export function useContentRevision(scope: ContentScope): number {
  return useSyncExternalStore(
    (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    () => revisions[scope],
    () => revisions[scope],
  );
}

export function resetContentRevisionsForTests(): void {
  revisions.documents = 0;
  revisions.attachments = 0;
}
