const globalForGenerationLocks = globalThis as typeof globalThis & {
  __toyGenerationLocks?: Set<string>;
};

function getLocks(): Set<string> {
  globalForGenerationLocks.__toyGenerationLocks ??= new Set<string>();
  return globalForGenerationLocks.__toyGenerationLocks;
}

export function startGenerationLock(key: string): (() => void) | null {
  const locks = getLocks();
  if (locks.has(key)) return null;
  locks.add(key);
  return () => {
    locks.delete(key);
  };
}
