"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.executeDataMigrations = void 0;
var _clientLambda = require("@webiny/aws-sdk/client-lambda");
var _utils = require("@webiny/cli-plugin-deploy-pulumi/utils");
var _cli = require("@webiny/data-migration/cli");
/**
 * On every deployment of the API project application, this plugin invokes the data migrations Lambda.
 */
const executeDataMigrations = exports.executeDataMigrations = {
  type: "hook-after-deploy",
  name: "hook-after-deploy-api-execute-data-migrations",
  async hook({
    inputs,
    env,
    projectApplication
  }, context) {
    // Only run migrations for `api` app
    if (projectApplication.id !== "api") {
      return;
    }
    if (inputs.build === false) {
      context.info(`"--no-build" argument detected - skipping data migrations.`);
      return;
    }

    // No need to run migrations if we're doing a preview.
    if (inputs.preview) {
      return;
    }
    const apiOutput = (0, _utils.getStackOutput)({
      folder: "apps/api",
      env,
      variant: inputs.variant || "",
      skipCache: true
    });
    context.info("Executing data migrations AWS Lambda function...");
    const logStreamingEnabled = process.env.WEBINY_MIGRATION_LOG_STREAMING !== "false";
    if (!logStreamingEnabled) {
      context.warning(["Data migration log streaming is disabled.", "Note that the logs will still be accessible in Amazon CloudWatch.", "Learn more: https://webiny.link/cloudwatch"].join(" "));
    }
    try {
      const lambdaClient = new _clientLambda.LambdaClient({
        region: apiOutput.region
      });
      const functionName = apiOutput["migrationLambdaArn"];
      const logReporter = new _cli.LogReporter(functionName);
      let statusReporter = new _cli.VoidStatusReporter();
      if (inputs.dataMigrationLogStreaming) {
        const useNonInteractiveReporter = !process.stdout.isTTY || "CI" in process.env;
        statusReporter = useNonInteractiveReporter ? new _cli.NonInteractiveCliStatusReporter(logReporter) : new _cli.InteractiveCliStatusReporter(logReporter);
      }
      const runner = _cli.MigrationRunner.create({
        lambdaClient,
        functionName,
        statusReporter
      });
      const result = await runner.runMigration({
        version: process.env.WEBINY_VERSION || context.version
      });
      if (result) {
        const reporter = new _cli.CliMigrationRunReporter(logReporter, context);
        await reporter.report(result);
      }
    } catch (e) {
      context.error(`An error occurred while executing data migrations Lambda function!`);
      console.log(e);
      throw e;
    }
  }
};

//# sourceMappingURL=executeDataMigrations.js.map