function toQuery(params) {
  const sp = new URLSearchParams();
  for (const [k, v] of Object.entries(params)) {
    if (v === void 0 || v === null) continue;
    if (Array.isArray(v)) {
      if (v.length === 0) continue;
      sp.set(k, v.join(","));
    } else {
      sp.set(k, String(v));
    }
  }
  return sp.toString();
}
function buildCrudQuery(params) {
  return toQuery(params);
}
import { apiCall, readApiResultOrThrow } from "./apiCall.js";
import { raiseCrudError } from "./serverErrors.js";
function mergeHeaders(base, extra) {
  if (!base) return extra;
  const hasHeadersCtor = typeof Headers !== "undefined";
  if (hasHeadersCtor && 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 fetchCrudList(apiPath, params, init) {
  const qs = buildCrudQuery(params);
  return readApiResultOrThrow(`/api/${apiPath}?${qs}`, init, {
    errorMessage: "Failed to fetch list"
  });
}
function buildCrudExportUrl(apiPath, params, format) {
  const qs = buildCrudQuery({ ...params, format });
  return `/api/${apiPath}?${qs}`;
}
function buildCrudCsvUrl(apiPath, params) {
  return buildCrudExportUrl(apiPath, params, "csv");
}
async function createCrud(apiPath, body, init) {
  const { parseResult, fallbackResult, errorMessage, headers, ...rest } = init ?? {};
  const call = await apiCall(
    `/api/${apiPath}`,
    {
      ...rest,
      method: "POST",
      headers: mergeHeaders(headers, { "content-type": "application/json" }),
      body: JSON.stringify(body)
    },
    {
      parse: parseResult,
      fallback: fallbackResult ?? null
    }
  );
  if (!call.ok) await raiseCrudError(call.response, errorMessage ?? "Failed to create");
  return call;
}
async function updateCrud(apiPath, body, init) {
  const { parseResult, fallbackResult, errorMessage, headers, ...rest } = init ?? {};
  const call = await apiCall(
    `/api/${apiPath}`,
    {
      ...rest,
      method: "PUT",
      headers: mergeHeaders(headers, { "content-type": "application/json" }),
      body: JSON.stringify(body)
    },
    {
      parse: parseResult,
      fallback: fallbackResult ?? null
    }
  );
  if (!call.ok) await raiseCrudError(call.response, errorMessage ?? "Failed to update");
  return call;
}
async function deleteCrud(apiPath, idOrOptions, maybeInit) {
  if (typeof idOrOptions === "string") {
    const { parseResult: parseResult2, fallbackResult: fallbackResult2, errorMessage: errorMessage2, ...rest2 } = maybeInit ?? {};
    const call2 = await apiCall(
      `/api/${apiPath}?id=${encodeURIComponent(idOrOptions)}`,
      {
        ...rest2,
        method: "DELETE"
      },
      {
        parse: parseResult2,
        fallback: fallbackResult2 ?? null
      }
    );
    if (!call2.ok) await raiseCrudError(call2.response, errorMessage2 ?? "Failed to delete");
    return call2;
  }
  const { parseResult, fallbackResult, errorMessage, headers, body, id, ...rest } = idOrOptions;
  const payload = body ?? (id ? { id } : void 0);
  const requestHeaders = payload !== void 0 ? mergeHeaders(headers, { "content-type": "application/json" }) : headers;
  const call = await apiCall(
    `/api/${apiPath}`,
    {
      ...rest,
      method: "DELETE",
      headers: requestHeaders,
      body: payload !== void 0 ? JSON.stringify(payload) : void 0
    },
    {
      parse: parseResult,
      fallback: fallbackResult ?? null
    }
  );
  if (!call.ok) await raiseCrudError(call.response, errorMessage ?? "Failed to delete");
  return call;
}
export {
  buildCrudCsvUrl,
  buildCrudExportUrl,
  buildCrudQuery,
  createCrud,
  deleteCrud,
  fetchCrudList,
  updateCrud
};
//# sourceMappingURL=crud.js.map
