import {
  filterCustomFieldDefs,
  fetchCustomFieldDefinitionsPayload
} from "./customFieldDefs.js";
import { FieldRegistry, loadGeneratedFieldRegistrations } from "../fields/registry.js";
import { apiCall } from "./apiCall.js";
import { normalizeCustomFieldOptions } from "@open-mercato/shared/modules/entities/options";
import { CURRENCY_OPTIONS_URL } from "@open-mercato/shared/modules/entities/kinds";
let registryReady = null;
async function ensureFieldRegistryReady() {
  if (!registryReady) {
    registryReady = loadGeneratedFieldRegistrations().catch((err) => {
      registryReady = null;
      throw err;
    });
  }
  await registryReady;
}
function buildOptionsUrl(base, query) {
  if (!query) return base;
  try {
    const isAbsolute = /^([a-z][a-z\d+\-.]*:)?\/\//i.test(base);
    const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
    const url = isAbsolute ? new URL(base) : new URL(base, origin);
    if (!url.searchParams.has("query")) url.searchParams.append("query", query);
    if (!url.searchParams.has("q")) url.searchParams.append("q", query);
    if (isAbsolute) return url.toString();
    return `${url.pathname}${url.search}`;
  } catch {
    const sep = base.includes("?") ? "&" : "?";
    if (base.includes("query=")) return `${base}${sep}q=${encodeURIComponent(query)}`;
    return `${base}${sep}query=${encodeURIComponent(query)}`;
  }
}
async function loadRemoteOptions(url) {
  try {
    const call = await apiCall(url, void 0, { fallback: { items: [] } });
    if (!call.ok) return [];
    const payload = call.result ?? { items: [] };
    const items = Array.isArray(payload?.items) ? payload.items : [];
    return items.map((it) => ({
      value: String(it?.value ?? it),
      label: String(it?.label ?? it?.value ?? it)
    }));
  } catch {
    return [];
  }
}
function buildFormFieldFromCustomFieldDef(def, opts) {
  const id = opts?.bareIds ? def.key : `cf_${def.key}`;
  const label = def.label || def.key;
  const required = Array.isArray(def.validation) ? def.validation.some((rule) => rule && rule.rule === "required") : false;
  const baseProps = {
    description: def.description,
    required,
    ...def.defaultValue !== void 0 && def.defaultValue !== null ? { defaultValue: def.defaultValue } : {}
  };
  switch (def.kind) {
    case "boolean":
      return { id, label, type: "checkbox", ...baseProps };
    case "integer":
    case "float":
      return { id, label, type: "number", ...baseProps };
    case "date":
      return { id, label, type: "datepicker", ...baseProps };
    case "datetime":
      return { id, label, type: "datetime", ...baseProps };
    case "multiline": {
      let editor = "html";
      if (def.editor === "simpleMarkdown") editor = "simple";
      else if (def.editor === "htmlRichText") editor = "html";
      return { id, label, type: "richtext", ...baseProps, editor };
    }
    case "select":
    case "currency":
    case "relation":
      return {
        id,
        label,
        type: "select",
        ...baseProps,
        options: normalizeCustomFieldOptions(def.options || []).map((option) => ({
          value: option.value,
          label: option.label
        })),
        multiple: !!def.multi,
        ...def.kind === "currency" ? {
          loadOptions: async (query) => {
            const url = buildOptionsUrl(CURRENCY_OPTIONS_URL, query);
            return loadRemoteOptions(url);
          }
        } : def.optionsUrl ? {
          loadOptions: async (query) => {
            const url = buildOptionsUrl(def.optionsUrl, query);
            return loadRemoteOptions(url);
          }
        } : {},
        ...def.multi && def.input === "listbox" ? { listbox: true } : {}
      };
    default: {
      if (def.kind === "text" && def.multi) {
        const base = { id, label, type: "tags", ...baseProps };
        const resolvedOptions = normalizeCustomFieldOptions(def.options || []);
        if (resolvedOptions.length > 0) {
          base.options = resolvedOptions.map((option) => ({ value: option.value, label: option.label }));
        }
        if (def.optionsUrl) {
          base.loadOptions = async (query) => {
            const url = buildOptionsUrl(def.optionsUrl, query);
            return loadRemoteOptions(url);
          };
        }
        return base;
      }
      if (def.kind === "text" && typeof def.editor === "string" && def.editor) {
        let editor = "html";
        if (def.editor === "simpleMarkdown") editor = "simple";
        else if (def.editor === "htmlRichText") editor = "html";
        return { id, label, type: "richtext", ...baseProps, editor };
      }
      const input = FieldRegistry.getInput(def.kind);
      if (input) {
        return {
          id,
          label,
          type: "custom",
          ...baseProps,
          component: (props) => input({ ...props, def })
        };
      }
      return { id, label, type: "text", ...baseProps };
    }
  }
}
function buildFormFieldsFromCustomFields(defs, opts) {
  const fields = [];
  const visible = filterCustomFieldDefs(defs, "form");
  const seenKeys = /* @__PURE__ */ new Set();
  for (const def of visible) {
    const keyLower = String(def.key).toLowerCase();
    if (seenKeys.has(keyLower)) continue;
    seenKeys.add(keyLower);
    const field = buildFormFieldFromCustomFieldDef(def, opts);
    if (field) fields.push(field);
  }
  return fields;
}
async function fetchCustomFieldFormStructure(entityIds, fetchImpl, options) {
  await ensureFieldRegistryReady();
  const metadata = await fetchCustomFieldDefinitionsPayload(entityIds, fetchImpl);
  const definitions = Array.isArray(metadata.items) ? metadata.items : [];
  const fields = buildFormFieldsFromCustomFields(definitions, options);
  return { fields, definitions, metadata };
}
async function fetchCustomFieldFormFields(entityIds, fetchImpl, options) {
  const { fields } = await fetchCustomFieldFormStructure(entityIds, fetchImpl, options);
  return fields;
}
async function fetchCustomFieldFormFieldsWithDefinitions(entityIds, fetchImpl, options) {
  return fetchCustomFieldFormStructure(entityIds, fetchImpl, options);
}
export {
  buildFormFieldFromCustomFieldDef,
  buildFormFieldsFromCustomFields,
  fetchCustomFieldFormFields,
  fetchCustomFieldFormFieldsWithDefinitions,
  fetchCustomFieldFormStructure
};
//# sourceMappingURL=customFieldForms.js.map
