import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPostForm } from "../../../lib/api/methods";
import { IMAGE_SCAN } from "./endpoint";
import { errorToast, successToast } from "../../../utils/toast";
import { SUCCESS_MESSAGES } from "./messages";


type ProviderResponse = {
  status: string;
  request: {
    id: string;
    timestamp: number;
    operations: number;
  };
  type: {
    ai_generated: number;
  };
  media: {
    id: string;
    uri: string;
  };
};

type ScanImageResponse = {
  status: string;
  type: string;
  aiGenerated: boolean;
  confidence: number;
  creditsRemaining: number;
  providerResponse: ProviderResponse;
};

export default function useImageScan() {
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["scan-image"],
    mutationFn: async (payload: FormData) => {
      const res = await apiPostForm<ScanImageResponse>(
        IMAGE_SCAN.SCAN,
        payload,
      );

      return res.data;
    },
    onSuccess: () => {
      successToast(SUCCESS_MESSAGES.SCAN_IMAGE);
      queryClient.invalidateQueries({ queryKey: ["credit-summary"] });
      queryClient.invalidateQueries({ queryKey: ["credit-history"] });
    },
    onError: (error: any) => {
      errorToast("Something went wrong.");
    },
  });

  return { scanImage: mutateAsync, loading: isPending };
}
