// utils/hooks/useGetMatches.ts
import axiosInstance from "@/lib/axios";
import { useQuery } from "@tanstack/react-query";

// useGetMatches.ts
const fetchFavorites = async (
  filters: Record<string, string>,
  page: number
) => {
  const userId = localStorage.getItem("userId");

  if (!userId) throw new Error("Missing user token or ID");

  const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

  const params = new URLSearchParams({
    page: page.toString(),
    per_page: "15",
  });

  // Append each filter only if it has a value
  Object.entries(filters).forEach(([key, value]) => {
    if (value && value.trim() !== "") {
      params.append(key, value);
    }
  });

  const { data } = await axiosInstance.get(
    `/users/${userId}/dashboard/favorites?${params.toString()}`
  );

  return data;
};

export const useGetFavorites = (
  filters: Record<string, string>,
  page: number
) => {
  return useQuery({
    queryKey: ["favorites", filters, page],
    queryFn: () => fetchFavorites(filters, page),
    staleTime: 1000 * 60 * 10,
    refetchOnWindowFocus: false,
    refetchOnMount: "always",
  });
};
