import { BASE_URL } from "@/components/main/BaseUrl";

export async function fetchPosts(
  page: number,
  limit: number,
  filters: {
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
    _id?: string;
    type?: string;
  },
  token: string
) {
  const validFilters = Object.entries(filters || {})
    .filter(([value]) => value !== undefined && value !== "")
    .reduce((acc, [key, value]) => {
      acc[key] = value;
      return acc;
    }, {} as Record<string, string>);

  const queryParams = new URLSearchParams({
    page: page.toString(),
    limit: limit.toString(),
    ...validFilters,
  }).toString();

  const apiUrl = `${BASE_URL}/users/web?${queryParams}`;

  const response = await fetch(apiUrl, {
    cache: "no-store",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  });

  if (!response.ok) {
    throw new Error(`Network response was not ok: ${response.status}`);
  }

  return response.json();
}