import { getApiBaseUrl } from "@/components/main/BaseUrl";
import { normalizeUserLevel } from "@/lib/userLevel";

export async function fetchPosts(
  page: number,
  limit: number,
  filters: {
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
    _id?: string;
    type?: string;
    exploreFilter?: string;
    subExpertise?: string;
    lat?: string;
    lng?: string;
    feedMode?: "grid" | "reels";
    seedPostId?: string;
    sort?: "latest";
  },
  token: string
) {
  const normalizedFilters = { ...filters };
  if (normalizedFilters.userLevel) {
    normalizedFilters.userLevel = normalizeUserLevel(normalizedFilters.userLevel);
  }

  const validFilters = Object.entries(normalizedFilters || {})
    .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 = `${getApiBaseUrl()}/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();
}