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

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

export interface UseLogPreviewResult {
  preview: LogPreviewResponse | null;
  loading: boolean;
  error: string | null;
  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 [error, setError] = useState<string | null>(null);

  const run = useCallback(async (req: LogPreviewRequest): Promise<void> => {
    setLoading(true);
    try {
      const resp = await previewLog(req);
      setPreview(resp);
      setError(null);
    } catch (err: unknown) {
      handleFetchError(err, setError, "Log preview failed");
    } finally {
      setLoading(false);
    }
  }, []);

  return { preview, loading, error, run };
}
