"use client";
import { apiFetch } from "./api.js";
import { raiseCrudError, readJsonSafe } from "./serverErrors.js";
import { createScopedHeaderStack } from "./scopedHeaderStack.js";
const scopedRequestHeaders = createScopedHeaderStack();
function mergeHeaders(base, extra) {
  if (!base) return extra;
  if (typeof Headers !== "undefined" && base instanceof Headers) {
    const merged = new Headers(base);
    Object.entries(extra).forEach(([key, value]) => merged.set(key, value));
    return merged;
  }
  if (Array.isArray(base)) {
    return [...base, ...Object.entries(extra)];
  }
  return { ...base, ...extra };
}
async function withScopedApiRequestHeaders(headers, run) {
  return scopedRequestHeaders.withScopedHeaders(headers, run);
}
async function apiCall(input, init, options) {
  const scopedHeaders = scopedRequestHeaders.resolveScopedHeaders();
  const requestInit = Object.keys(scopedHeaders).length > 0 ? { ...init ?? {}, headers: mergeHeaders(init?.headers, scopedHeaders) } : init;
  const response = await apiFetch(input, requestInit);
  const parser = options?.parse;
  const fallback = options?.fallback ?? null;
  let result = null;
  const rawCacheStatus = response.headers?.get?.("x-om-cache") ?? response.headers?.get?.("x-cache-status") ?? null;
  const cacheStatus = rawCacheStatus === "hit" || rawCacheStatus === "miss" ? rawCacheStatus : null;
  try {
    const source = typeof response.clone === "function" ? response.clone() : response;
    if (parser) result = await parser(source);
    else result = await readJsonSafe(source, fallback);
  } catch {
    result = fallback;
  }
  return {
    ok: response.ok,
    status: response.status,
    result,
    response,
    cacheStatus
  };
}
async function apiCallOrThrow(input, init, options) {
  const { errorMessage, ...callOptions } = options ?? {};
  const call = await apiCall(input, init, callOptions);
  if (!call.ok) {
    await raiseCrudError(call.response, errorMessage);
  }
  return call;
}
async function readApiResultOrThrow(input, init, options) {
  const { allowNullResult = false, emptyResultMessage, ...callOptions } = options ?? {};
  const call = await apiCallOrThrow(input, init, callOptions);
  if (call.result == null && !allowNullResult) {
    const fallback = emptyResultMessage ?? callOptions.errorMessage ?? `Missing response payload (${call.status})`;
    throw new Error(fallback);
  }
  return call.result;
}
export {
  apiCall,
  apiCallOrThrow,
  readApiResultOrThrow,
  withScopedApiRequestHeaders
};
//# sourceMappingURL=apiCall.js.map
