import { config } from "../../../../../config/index.js";
import { FileUploadField } from "../../components/index.js";
const designerUrl = config.get('designerUrl');
export function format(context, items, model, _submitResponse, _formStatus) {
  const now = new Date();
  const categorisedData = categoriseData(items);
  const meta = {
    schemaVersion: '2',
    timestamp: now.toISOString(),
    definition: model.def,
    referenceNumber: context.referenceNumber
  };
  const data = {
    meta,
    data: categorisedData
  };
  const body = JSON.stringify(data);
  return body;
}

/**
 * Categories the form submission data into the "main" body and "repeaters".
 *
 * {
 *    main: {
 *       componentName: 'componentValue',
 *    },
 *    repeaters: {
 *      repeaterName: [
 *        {
 *          textComponentName: 'componentValue'
 *        },
 *        {
 *          richComponentName: { foo: 'bar', 'baz': true }
 *        }
 *      ]
 *    },
 *    files: {
 *      fileComponentName: [
 *        {
 *          fileId: '123-456-789',
 *          fileName: 'example.pdf',
 *          userDownloadLink: 'https://forms-designer/file-download/123-456-789'
 *        }
 *      ]
 *    }
 * }
 */
export function categoriseData(items) {
  const output = {
    main: {},
    repeaters: {},
    files: {}
  };
  items.forEach(item => {
    const {
      name,
      state
    } = item;
    if ('subItems' in item) {
      output.repeaters[name] = extractRepeaters(item);
    } else if (isFileUploadFieldItem(item)) {
      output.files[name] = extractFileUploads(item);
    } else {
      output.main[name] = item.field.getFormValueFromState(state);
    }
  });
  return output;
}

/**
 * Returns the "repeaters" section of the response body
 * @param item - the repeater item
 * @returns the repeater item
 */
function extractRepeaters(item) {
  const repeaters = [];
  item.subItems.forEach(inputRepeaterItem => {
    const outputRepeaterItem = {};
    inputRepeaterItem.forEach(repeaterComponent => {
      const {
        field,
        state
      } = repeaterComponent;
      outputRepeaterItem[repeaterComponent.name] = field.getFormValueFromState(state);
    });
    repeaters.push(outputRepeaterItem);
  });
  return repeaters;
}

/**
 * Returns the "files" section of the response body
 * @param item - the file upload item in the form
 * @returns the file upload data
 */
function extractFileUploads(item) {
  const fileUploadState = item.field.getFormValueFromState(item.state) ?? [];
  return fileUploadState.map(fileState => {
    const {
      file
    } = fileState.status.form;
    return {
      fileId: file.fileId,
      fileName: file.filename,
      userDownloadLink: `${designerUrl}/file-download/${file.fileId}`
    };
  });
}
function isFileUploadFieldItem(item) {
  return item.field instanceof FileUploadField;
}
//# sourceMappingURL=v2.js.map