import {
  useMutation,
  useQuery,
  useQueryClient,
  useInfiniteQuery,
} from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import { createBookmarkApi } from "~/utils/api-client-factory";

export function useServiceBookmarkProduct() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (productId: string) => {
      const bookmarkApi = createBookmarkApi(token);
      return await bookmarkApi.apiEngagementV1BookmarksCreate({
        data: { productId },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getUserBookmarksService"] });
      queryClient.invalidateQueries({ queryKey: ["checkBookmarkService"] });
    },
  });
}

export function useServiceDeleteBookmark() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (productId: string) => {
      const bookmarkApi = createBookmarkApi(token);
      await bookmarkApi.apiEngagementV1BookmarksDelete({ productId });
      return { success: true };
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getUserBookmarksService"] });
      queryClient.invalidateQueries({ queryKey: ["checkBookmarkService"] });
    },
  });
}

export function useServiceCheckBookmark(productId: string) {
  const token = useAuthToken();
  const response = useQuery({
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["checkBookmarkService", productId],
    queryFn: async () => {
      const bookmarkApi = createBookmarkApi(token);
      return await bookmarkApi.apiEngagementV1BookmarksCheckRead({ productId });
    },
    enabled: !!token && !!productId,
  });

  return { ...response };
}

export function useServiceGetUserBookmarks() {
  const token = useAuthToken();
  const response = useInfiniteQuery({
    queryKey: ["getUserBookmarksService"],
    queryFn: async ({ pageParam = 1 }) => {
      const bookmarkApi = createBookmarkApi(token);
      const bookmarks = await bookmarkApi.apiEngagementV1BookmarksListList({
        page: pageParam,
        pageSize: 12,
      });

      // Since the API returns an array instead of a paginated response object,
      // we'll construct a pagination-compatible response
      return {
        results: bookmarks.results,
        next: bookmarks.next,
        previous: bookmarks.previous,
      };
    },
    initialPageParam: 1,
    getNextPageParam: (lastPage) => {
      if (lastPage.next) {
        const url = new URL(lastPage.next, import.meta.env.VITE_API_BASE_URL);
        const page = url.searchParams.get("page");
        return page ? parseInt(page) : undefined;
      }
      return undefined;
    },
    enabled: !!token,
  });

  return { ...response };
}
