import { categoriseData } from "../machine/v2.js";
import { FormAdapterSubmissionSchemaVersion } from "../../types/enums.js";
import { FormStatus } from "../../../../routes/types.js";
export function format(context, items, model, submitResponse, formStatus, formMetadata) {
  const csvFiles = extractCsvFiles(submitResponse);
  const {
    main: v2Main,
    ...v2Data
  } = categoriseData(items);
  const versionMetadata = getVersionMetadata(context.submittedVersionNumber, formMetadata);
  const meta = {
    schemaVersion: FormAdapterSubmissionSchemaVersion.V1,
    timestamp: new Date(),
    referenceNumber: context.referenceNumber,
    formName: model.name,
    formId: formMetadata?.id ?? '',
    formSlug: formMetadata?.slug ?? '',
    status: formStatus.isPreview ? FormStatus.Draft : FormStatus.Live,
    isPreview: formStatus.isPreview,
    notificationEmail: formMetadata?.notificationEmail ?? ''
  };
  if (versionMetadata) {
    meta.versionMetadata = versionMetadata;
  }
  const main = Object.fromEntries(Object.entries(v2Main).map(([key, value]) => {
    if (value === undefined) {
      return [key, null];
    }
    return [key, value];
  }));
  const data = {
    main,
    ...v2Data
  };
  const result = {
    files: csvFiles
  };
  const payload = {
    meta,
    data,
    result
  };
  return JSON.stringify(payload);
}
export function getVersionMetadata(submittedVersionNumber, formMetadata) {
  if (!formMetadata?.versions?.length) {
    return undefined;
  }
  if (submittedVersionNumber !== undefined) {
    const submittedVersion = formMetadata.versions.find(v => v.versionNumber === submittedVersionNumber);
    if (submittedVersion) {
      return {
        versionNumber: submittedVersion.versionNumber,
        createdAt: submittedVersion.createdAt
      };
    }
  }

  // fallback to first available version
  const firstVersion = formMetadata.versions[0];
  return {
    versionNumber: firstVersion.versionNumber,
    createdAt: firstVersion.createdAt
  };
}
function extractCsvFiles(submitResponse) {
  const result = submitResponse.result;
  return {
    main: result.files?.main ?? '',
    repeaters: result.files?.repeaters ?? {}
  };
}
//# sourceMappingURL=v1.js.map