/* eslint-disable @typescript-eslint/no-unused-vars */
import { getApiBaseUrl } from "@/components/main/BaseUrl";

export async function fetchProjects(
  page: number,
  limit: number,
  filters: {
    expertise?: string;
    most_requests?: string;
    most_price?: string;
    age?: string;
    gender?: 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,
    timestamp: Date.now().toString(), // اضافه کردن timestamp برای جلوگیری از کش
  }).toString();

  const apiUrl = `${getApiBaseUrl()}/projects?${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");
  }

  return response.json();
}
