const API_BASE =
  process.env.NEXT_PUBLIC_API_URL ?? "";

export interface AdminMerchantCategoryMapping {
  id: number;
  merchantId: number;
  merchantName: string;
  rawCategoryPath: string;
  partCategorySlug: string | null;
}

export async function fetchMerchantCategoryMappings(
  token: string,
  filters?: { merchantId?: number }
): Promise<AdminMerchantCategoryMapping[]> {
  const params = new URLSearchParams();

  if (filters?.merchantId) {
    params.append("merchantId", String(filters.merchantId));
  }

  const res = await fetch(
    `${API_BASE}/api/admin/category-mappings?${params.toString()}`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      cache: "no-store",
    }
  );

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`API error ${res.status}: ${text}`);
  }

  return res.json();
}

export async function updateMerchantCategoryMapping(
  token: string,
  id: number,
  payload: { partCategorySlug: string | null }
): Promise<AdminMerchantCategoryMapping> {
  const res = await fetch(`${API_BASE}/api/admin/category-mappings/${id}`, {
    method: "PUT",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`API error ${res.status}: ${text}`);
  }

  return res.json();
}