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

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

export interface UseRegexTesterResult {
  result: RegexTestResponse | null;
  testing: boolean;
  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 test = useCallback(async (req: RegexTestRequest): Promise<void> => {
    setTesting(true);
    try {
      const resp = await testRegex(req);
      setResult(resp);
    } catch (err: unknown) {
      if (err instanceof Error) {
        setResult({ matched: false, groups: [], error: err.message });
      }
    } finally {
      setTesting(false);
    }
  }, []);

  return { result, testing, test };
}
