/* eslint-disable */
/**
 * This file was automatically generated by scripts/manifest/migrate-ts.mustache.
 * DO NOT MODIFY IT BY HAND. Instead, modify scripts/manifest/migrate-ts.mustache,
 * and run node ./scripts/manifest/generateFormatTypes.js to regenerate this file.
 */
import {
  Any{{#latest}}{{type}}{{/latest}},
  {{#latest}}{{type}}{{/latest}},
  {{#latest}}{{type}}{{/latest}}Formats,
} from ".";
import { findShortestMigrationPath } from "../../migrations";
import { migrators } from "./migrators";
import { ILogger } from "@polywrap/logging-js";

export function migrate{{#latest}}{{type}}{{/latest}}(
  manifest: Any{{#latest}}{{type}}{{/latest}},
  to: {{#latest}}{{type}}{{/latest}}Formats,
  logger?: ILogger
): {{#latest}}{{type}}{{/latest}} {
  let from = manifest.format as {{#latest}}{{type}}{{/latest}}Formats;

  if (!(Object.values({{#latest}}{{type}}{{/latest}}Formats).some(x => x === from))) {
    throw new Error(`Unrecognized {{#latest}}{{type}}{{/latest}}Format "${manifest.format}"`);
  }

  if (!(Object.values({{#latest}}{{type}}{{/latest}}Formats).some(x => x === to))) {
    throw new Error(`Unrecognized {{#latest}}{{type}}{{/latest}}Format "${to}"`);
  }

  const migrationPath = findShortestMigrationPath(migrators, from, to);
  if (!migrationPath) {
    throw new Error(
      `Migration path from {{#latest}}{{type}}{{/latest}}Format "${from}" to "${to}" is not available`
    );
  }

  let newManifest = manifest;

  for(const migrator of migrationPath){
    newManifest = migrator.migrate(newManifest, logger) as Any{{#latest}}{{type}}{{/latest}};
  }

  return newManifest as {{#latest}}{{type}}{{/latest}};
}
