const EXTERNAL_URL = Deno.env.get("EXTERNAL_SUPABASE_URL")!;
const EXTERNAL_KEY = Deno.env.get("EXTERNAL_SUPABASE_KEY")!;

async function externalRest(
  path: string,
  method: string = "GET",
  body?: any,
  params?: Record<string, string>
) {
  let url = `${EXTERNAL_URL}${path}`;
  if (params) {
    url += `?${new URLSearchParams(params).toString()}`;
  }

  const res = await fetch(url, {
    method,
    headers: {
      apikey: EXTERNAL_KEY,
      Authorization: `Bearer ${EXTERNAL_KEY}`,
      "Content-Type": "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  const text = await res.text();
  try {
    return { status: res.status, data: JSON.parse(text) };
  } catch {
    return { status: res.status, data: text };
  }
}

export { externalRest };
