/**
 * React hook for running a regex test request.
 */

import { useCallback, useState } from "react";
import { testRegex } from "../api/config";
import { handleFetchError, createStringErrorAdapter } from "../utils/fetchError";
import type { RegexTestRequest, RegexTestResponse } from "../types/config";

export interface UseRegexTesterResult {
  result: RegexTestResponse | null;
  testing: boolean;
  error: string | null;
  test: (req: RegexTestRequest) => Promise<void>;
}

/**
 * Execute regex tests and expose the current response.
 */
export function useRegexTester(): UseRegexTesterResult {
  const [result, setResult] = useState<RegexTestResponse | null>(null);
  const [testing, setTesting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const test = useCallback(async (req: RegexTestRequest): Promise<void> => {
    setTesting(true);
    try {
      const resp = await testRegex(req);
      setResult(resp);
      setError(null);
    } catch (err: unknown) {
      handleFetchError(err, createStringErrorAdapter(setError), "Regex test failed");
    } finally {
      setTesting(false);
    }
  }, []);

  return { result, testing, error, test };
}
