import {
  type QueryKey,
  useMutation,
  useQueryClient,
} from '@tanstack/react-query';

import { useApiClient } from '@/lib/apiClient';

interface StartImageGenerationParams {
  generatedTextId?: string;
  prompt: string;
  clipId?: string;
  quantity?: number;
  models?: ('sdxl-lightning' | 'openai_image_gpt_1' | 'fal_nano_banana')[];
}

interface UseStartImageGenerationOptions {
  invalidateQueryKey?: QueryKey;
}

export function useStartImageGeneration(
  options?: UseStartImageGenerationOptions
) {
  const apiClient = useApiClient();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: async (params: StartImageGenerationParams) => {
      const { data, error } = await apiClient.POST(
        '/api/video_gen/image/generate',
        {
          body: {
            generated_text_id: params.generatedTextId || undefined,
            prompt: params.prompt,
            clip_id: params.clipId,
            quantity: params.quantity ?? 2,
            models: params.models ?? [],
          },
        }
      );

      if (error || !data) {
        throw new Error('Failed to start image generation');
      }

      return data;
    },
    onSuccess: () => {
      if (options?.invalidateQueryKey) {
        // Clear the cache so remounting fetches fresh data with new generation
        queryClient.removeQueries({
          queryKey: options.invalidateQueryKey,
        });
      }
    },
  });

  return mutation.mutateAsync;
}
