import { useEffect } from "react";
import type { Generation, GenerationKind } from "../lib/generations";

/**
 * The shape each generator's prefill callback expects. Tools accept `prefill`
 * (a Generation) and call this hook to consume it once. The hook calls
 * `onConsumed` to tell the parent to clear the pending prefill, so re-renders
 * don't re-trigger the effect.
 */
export function usePrefillEffect<T extends Generation>(
  prefill: T | null,
  kind: GenerationKind,
  onConsumed: () => void,
  apply: (data: T) => void,
) {
  useEffect(() => {
    if (prefill && prefill.kind === kind) {
      apply(prefill as T);
      onConsumed();
    }
    // Intentional: run only when prefill id changes (mount or rehydrate).
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [prefill?.id]);
}
