/**
 * React hook for fetching a server log preview.
 */

import { useCallback, useState } from "react";
import { previewLog } from "../api/config";
import type { LogPreviewRequest, LogPreviewResponse } from "../types/config";

export interface UseLogPreviewResult {
  preview: LogPreviewResponse | null;
  loading: boolean;
  run: (req: LogPreviewRequest) => Promise<void>;
}

/**
 * Execute a log preview and expose the response state.
 */
export function useLogPreview(): UseLogPreviewResult {
  const [preview, setPreview] = useState<LogPreviewResponse | null>(null);
  const [loading, setLoading] = useState(false);

  const run = useCallback(async (req: LogPreviewRequest): Promise<void> => {
    setLoading(true);
    try {
      const resp = await previewLog(req);
      setPreview(resp);
    } catch (err: unknown) {
      if (err instanceof Error) {
        setPreview({
          lines: [],
          total_lines: 0,
          matched_count: 0,
          regex_error: err.message,
        });
      }
    } finally {
      setLoading(false);
    }
  }, []);

  return { preview, loading, run };
}
