import { useInfiniteQuery } from "@tanstack/react-query";
import { useCallback } from "react";
import { PaginatedExploreProduct } from "../../src/api/types/models";
import { createApiApi } from "~/utils/api-client-factory";

// Define the Product type to match the API response
export type Product = {
  id: string;
  image: string;
  title?: string;
  price?: number;
  created_at?: string;
};

// Create a new API instance (no token needed for explore)
const apiInstance = createApiApi();

/**
 * Custom hook for infinite product loading using cursor-based pagination
 */
export const useProductsInfiniteQuery = () => {
  // Function to get next page URL from previous result
  const getNextPageParam = useCallback((lastPage: PaginatedExploreProduct) => {
    return lastPage.next || undefined;
  }, []);

  return useInfiniteQuery({
    queryKey: ["products"],
    queryFn: async ({ pageParam }) => {
      // If pageParam is a full URL, extract the cursor
      let cursor: string | undefined = undefined;
      if (typeof pageParam === "string" && pageParam.includes("cursor=")) {
        const url = new URL(pageParam);
        const cursorParam = url.searchParams.get("cursor");
        if (cursorParam) cursor = cursorParam;
      } else if (typeof pageParam === "string") {
        cursor = pageParam;
      }

      // Call the API with the cursor if available
      return await apiInstance.apiExploreV1List({
        cursor: cursor,
      });
    },
    getNextPageParam,
    initialPageParam: undefined,
  });
};
