export async function loadMonitorWorkspace(route, fetchImpl = fetch) {
  const params = new URLSearchParams(compact(route.filters));
  return requestJson(fetchImpl, `/api/monitor/workspace?${params}`);
}

export async function loadMonitorRun(route, fetchImpl = fetch) {
  const params = new URLSearchParams(compact({ sentinelId: route.filters.sentinelId, node: route.filters.node, lane: route.filters.lane }));
  return requestJson(fetchImpl, `/api/monitor/runs/${encodeURIComponent(route.runId)}?${params}`);
}

function compact(value) {
  return Object.fromEntries(Object.entries(value).filter(([, item]) => item));
}

async function requestJson(fetchImpl, path) {
  const response = await fetchImpl(path, { cache: "no-store", headers: { accept: "application/json" } });
  const body = await response.json().catch(() => null);
  if (!response.ok || !body?.ok) throw Object.assign(new Error(body?.error?.code || `http_${response.status}`), { status: response.status, body });
  return body;
}
