import { getTranslations } from "next-intl/server";
import { getToken } from "./cookies";

export async function postAsFormData(url, data) {
  const token = await getToken();
  // 1. Build FormData
  const formData = new FormData();
  for (const [key, value] of Object.entries(data)) {
    // If the value is a File or Blob, FormData handles it natively
    formData.append(key, value);
  }

  // 2. Send the request
  const response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${url}`, {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
    },
    credentials: "include",
  });

  // 3. Handle 401 explicitly
  if (response.status === 401) {
    throw {
      error: true,
      code: 401,
    };
  }

  // 4. Other errors
  if (!response.ok) {
    throw {
      error: true,
      code: 401,
    };
  }

  // 5. Parse JSON (adjust if you expect e.g. plain text)
  return response?.json();
}
