"use strict";

exports.__esModule = true;
exports.defineSchemaSource = defineSchemaSource;
/** A field type a source allows creating. The label keys are resolved to text by the UI. */

/** Collection-query config derived from a source, ready to spread into a collection hook. */

/** What a caller passes. Only `collectionId` and `loadSchema` are required. */

/** The resolved source: defaults filled, `loadSchema` memoized. */

/** Fills source-neutral defaults over `input` and memoizes the load so the collection
 *  query and the table columns share a single fetch. */
function defineSchemaSource(input) {
  const {
    collectionId,
    paginationMode = 'offset',
    creatableFieldTypes = [],
    fieldPermissions,
    supportsPii = false
  } = input;
  let loaded;
  let schema;
  const loadSchema = () => loaded ?? (loaded = input.loadSchema().then(result => {
    schema = result.schema;
    return result;
  }).catch(error => {
    loaded = undefined;
    throw error;
  }));
  const searchableFieldIds = input.searchableFieldIds ?? (s => [s.displayField]);
  const itemKey = input.itemKey ?? (item => {
    var _schema;
    return String(item[((_schema = schema) == null ? void 0 : _schema.idField) ?? '_id'] ?? '');
  });
  const itemName = input.itemName ?? (item => {
    var _schema2;
    return String(item[((_schema2 = schema) == null ? void 0 : _schema2.displayField) ?? '_id'] ?? '');
  });
  const canAddFields = input.canAddFields ?? (s => {
    var _s$schemaPermissions;
    return ((_s$schemaPermissions = s.schemaPermissions) == null ? void 0 : _s$schemaPermissions.createField) ?? false;
  });
  const canEditField = input.canEditField ?? ((field, s) => {
    var _s$schemaPermissions2;
    return (((_s$schemaPermissions2 = s.schemaPermissions) == null ? void 0 : _s$schemaPermissions2.updateField) ?? false) && !field.isSystem;
  });
  const canDeleteField = input.canDeleteField ?? ((field, s) => {
    var _s$schemaPermissions3;
    return (((_s$schemaPermissions3 = s.schemaPermissions) == null ? void 0 : _s$schemaPermissions3.deleteField) ?? false) && !field.isSystem;
  });
  const fetchData = async query => {
    const {
      backend,
      schema: loadedSchema
    } = await loadSchema();
    return backend.find(query, {
      searchableFieldIds: searchableFieldIds(loadedSchema)
    });
  };
  return {
    collectionId,
    loadSchema,
    collectionConfig: {
      queryName: collectionId,
      paginationMode,
      fetchData,
      itemKey,
      itemName
    },
    creatableFieldTypes,
    searchableFieldIds,
    canAddFields,
    canEditField,
    canDeleteField,
    fieldPermissions,
    supportsPii
  };
}
//# sourceMappingURL=SchemaSource.js.map