import { API_ENDPOINTS, tendersService } from "@/lib/api";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
import { toast } from "react-toastify";

export const useTendersQuery = (params?: Record<string, any>) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.TENDERS.READ_ALL, "read-tenders", params],
    [params],
  );

  return useQuery({
    queryKey,
    queryFn: () => tendersService.tendersList({ ...params }),
  });
};

export const useTenderDetailQuery = (id: string, params?: Record<string, any>) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.TENDERS.DETAILS(id), params],
    [id, params],
  );
  return useQuery({
    queryKey,
    queryFn: () => tendersService.tenderDetails(id, params),
  });
};

export const useTranslateTenderMutation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: [API_ENDPOINTS.TENDERS.AI_TRANSLATE("translate")],
    mutationFn: tendersService.translateTender,
    onSuccess: (_, variables) => {
      toast.success(`Translation for "${variables.language}" is ready`);
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.TENDERS.READ_ALL],
      });
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.TENDERS.DETAILS(variables.id)],
      });
    },
    onError: () => {
      toast.error(
        "Translation temporarily unavailable. Showing original content.",
      );
    },
  });
};
export const useGetTenderDocumentsQuery = (
  id: string,
  options?: { enabled?: boolean },
) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.TENDERS.DOCUMENTS(id)],
    [id],
  );
  return useQuery({
    queryKey,
    queryFn: () => tendersService.getDocuments(id),
    enabled: options?.enabled ?? true,
  });
};