/**
 * React hook for triggering a manual blocklist import run.
 */

import { useCallback, useState } from "react";
import { runImportNow } from "../api/blocklist";
import { handleFetchError } from "../utils/fetchError";
import type { ImportRunResult } from "../types/blocklist";

export interface UseRunImportReturn {
  running: boolean;
  lastResult: ImportRunResult | null;
  error: string | null;
  runNow: () => Promise<void>;
}

/**
 * Trigger and track a manual blocklist import run.
 */
export function useRunImport(): UseRunImportReturn {
  const [running, setRunning] = useState(false);
  const [lastResult, setLastResult] = useState<ImportRunResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  const runNow = useCallback(async (): Promise<void> => {
    setRunning(true);
    setError(null);
    try {
      const result = await runImportNow();
      setLastResult(result);
    } catch (err: unknown) {
      handleFetchError(err, setError, "Import failed");
    } finally {
      setRunning(false);
    }
  }, []);

  return { running, lastResult, error, runNow };
}
