import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { readApiResultOrThrow } from "./apiCall.js";
function normalizeEntityIds(entityIds) {
  if (entityIds == null) return [];
  const list = Array.isArray(entityIds) ? entityIds : [entityIds];
  const dedup = /* @__PURE__ */ new Set();
  const normalized = [];
  for (const raw of list) {
    const trimmed = String(raw ?? "").trim();
    if (!trimmed || dedup.has(trimmed)) continue;
    dedup.add(trimmed);
    normalized.push(trimmed);
  }
  return normalized;
}
function buildDefinitionsQuery(entityIds, options) {
  const params = new URLSearchParams();
  entityIds.forEach((id) => {
    if (id) params.append("entityId", id);
  });
  if (options?.fieldset) params.set("fieldset", options.fieldset);
  return params.toString();
}
function normalizeRecord(value) {
  if (!value || typeof value !== "object") return {};
  const out = {};
  for (const [key, raw] of Object.entries(value)) {
    if (!Array.isArray(raw)) continue;
    out[key] = raw;
  }
  return out;
}
function preparePayload(data) {
  const items = Array.isArray(data?.items) ? [...data.items] : [];
  items.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
  const fieldsetsByEntity = normalizeRecord(data?.fieldsetsByEntity);
  const entitySettings = data?.entitySettings && typeof data.entitySettings === "object" ? data.entitySettings : {};
  return { items, fieldsetsByEntity, entitySettings };
}
async function readDefinitionsViaFetch(entityIds, fetchImpl, options) {
  const query = buildDefinitionsQuery(entityIds, options);
  const res = await fetchImpl(`/api/entities/definitions?${query}`, {
    headers: { "content-type": "application/json" }
  });
  const data = await res.json().catch(() => ({ items: [] }));
  return preparePayload(data);
}
async function readDefinitionsViaApi(entityIds, options) {
  const query = buildDefinitionsQuery(entityIds, options);
  const payload = await readApiResultOrThrow(
    `/api/entities/definitions?${query}`,
    { headers: { "content-type": "application/json" } },
    {
      errorMessage: "Failed to load custom field definitions",
      fallback: { items: [] }
    }
  );
  return preparePayload(payload);
}
async function fetchCustomFieldDefinitionsPayload(entityIds, fetchImpl, options) {
  const filtered = normalizeEntityIds(entityIds);
  if (!filtered.length) return { items: [] };
  return fetchImpl ? await readDefinitionsViaFetch(filtered, fetchImpl, options) : await readDefinitionsViaApi(filtered, options);
}
async function fetchCustomFieldDefs(entityIds, fetchImpl, options) {
  const payload = await fetchCustomFieldDefinitionsPayload(entityIds, fetchImpl, options);
  return payload.items ?? [];
}
function useCustomFieldDefs(entityIds, options = {}) {
  const {
    enabled: enabledOption = true,
    staleTime,
    gcTime,
    keyExtras,
    fetchImpl,
    fieldset
  } = options;
  const normalizedIds = React.useMemo(() => normalizeEntityIds(entityIds), [entityIds]);
  const idsSignature = React.useMemo(() => JSON.stringify(normalizedIds), [normalizedIds]);
  const extrasSignature = React.useMemo(() => JSON.stringify(keyExtras ?? []), [keyExtras]);
  const normalizedFieldset = typeof fieldset === "string" && fieldset.trim().length ? fieldset.trim() : null;
  const queryKey = React.useMemo(
    () => ["customFieldDefs", ...keyExtras ?? [], ...normalizedIds, `fieldset:${normalizedFieldset ?? "default"}`],
    [idsSignature, extrasSignature, normalizedFieldset]
  );
  const enabled = enabledOption && normalizedIds.length > 0;
  return useQuery({
    queryKey,
    queryFn: () => fetchCustomFieldDefs(
      normalizedIds,
      fetchImpl,
      normalizedFieldset ? { fieldset: normalizedFieldset } : void 0
    ),
    enabled,
    staleTime: staleTime ?? 5 * 60 * 1e3,
    gcTime: gcTime ?? 30 * 60 * 1e3,
    select: options.select
  });
}
function isDefVisible(def, mode) {
  switch (mode) {
    case "list":
      return def.listVisible !== false;
    case "form":
      return def.formEditable !== false;
    case "filter":
      return !!def.filterable;
    default:
      return true;
  }
}
function filterCustomFieldDefs(defs, mode) {
  return defs.filter((d) => isDefVisible(d, mode)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
}
async function invalidateCustomFieldDefs(queryClient, entityIds) {
  const normalizedIds = normalizeEntityIds(entityIds);
  const targetPrefixes = /* @__PURE__ */ new Set(["customFieldDefs", "customFieldForms", "dealFormFields"]);
  if (!normalizedIds.length) {
    await queryClient.invalidateQueries({
      predicate: (query) => Array.isArray(query.queryKey) && typeof query.queryKey[0] === "string" && targetPrefixes.has(query.queryKey[0])
    });
    return;
  }
  await queryClient.invalidateQueries({
    predicate: (query) => {
      if (!Array.isArray(query.queryKey)) return false;
      const [prefix] = query.queryKey;
      if (typeof prefix !== "string" || !targetPrefixes.has(prefix)) return false;
      return normalizedIds.every((id) => query.queryKey.includes(id));
    }
  });
}
export {
  fetchCustomFieldDefinitionsPayload,
  fetchCustomFieldDefs,
  filterCustomFieldDefs,
  invalidateCustomFieldDefs,
  isDefVisible,
  normalizeEntityIds,
  useCustomFieldDefs
};
//# sourceMappingURL=customFieldDefs.js.map
