"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chunk_TDN3QQTH_exports = {};
__export(chunk_TDN3QQTH_exports, {
  MigrateStatus: () => MigrateStatus
});
module.exports = __toCommonJS(chunk_TDN3QQTH_exports);
var import_chunk_QOPTDDIH = require("./chunk-QOPTDDIH.js");
var import_chunk_BRPS327A = require("./chunk-BRPS327A.js");
var import_chunk_RGXJYLMD = require("./chunk-RGXJYLMD.js");
var import_chunk_SKRR5WT4 = require("./chunk-SKRR5WT4.js");
var import_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var debug = (0, import_debug.default)("prisma:migrate:status");
var MigrateStatus = class _MigrateStatus {
  static new() {
    return new _MigrateStatus();
  }
  static help = (0, import_internals.format)(`
Check the status of your database migrations

  ${(0, import_chunk_SKRR5WT4.bold)("Usage")}

    ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate status [options]

    The datasource URL configuration is read from the Prisma config file (e.g., ${(0, import_chunk_SKRR5WT4.italic)("prisma.config.ts")}).

  ${(0, import_chunk_SKRR5WT4.bold)("Options")}

  -h, --help   Display this help message
    --config   Custom path to your Prisma config file
    --schema   Custom path to your Prisma schema

  ${(0, import_chunk_SKRR5WT4.bold)("Examples")}

  Check the status of your database migrations
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate status

  Specify a schema
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate status --schema=./schema.prisma
`);
  async parse(argv, config, baseDir) {
    const args = (0, import_internals.arg)(
      argv,
      {
        "--help": Boolean,
        "-h": "--help",
        "--schema": String,
        "--config": String,
        "--telemetry-information": String
      },
      false
    );
    if ((0, import_internals.isError)(args)) {
      return this.help(args.message);
    }
    if (args["--help"]) {
      return this.help();
    }
    const schemaContext = await (0, import_internals.loadSchemaContext)({
      schemaPath: (0, import_internals.createSchemaPathInput)({
        schemaPathFromArgs: args["--schema"],
        schemaPathFromConfig: config.schema,
        baseDir
      })
    });
    const { migrationsDirPath } = (0, import_internals.inferDirectoryConfig)(schemaContext, config);
    const cmd = "migrate status";
    const validatedConfig = (0, import_internals.validatePrismaConfigWithDatasource)({ config, cmd });
    (0, import_internals.checkUnsupportedDataProxy)({ cmd, validatedConfig });
    (0, import_chunk_QOPTDDIH.printDatasource)({ datasourceInfo: (0, import_chunk_BRPS327A.parseDatasourceInfo)(schemaContext.primaryDatasource, validatedConfig) });
    const schemaFilter = {
      externalTables: config.tables?.external ?? [],
      externalEnums: config.enums?.external ?? []
    };
    const migrate = await import_chunk_RGXJYLMD.Migrate.setup({
      schemaEngineConfig: config,
      baseDir,
      migrationsDirPath,
      schemaContext,
      schemaFilter,
      extensions: config["extensions"]
    });
    await (0, import_chunk_BRPS327A.ensureCanConnectToDatabase)(baseDir, validatedConfig);
    let diagnoseResult;
    let listMigrationDirectoriesResult;
    try {
      diagnoseResult = await migrate.diagnoseMigrationHistory({
        optInToShadowDatabase: false
      });
      debug({ diagnoseResult: JSON.stringify(diagnoseResult, null, 2) });
      listMigrationDirectoriesResult = await migrate.listMigrationDirectories();
      debug({ listMigrationDirectoriesResult });
    } finally {
      await migrate.stop();
    }
    process.stdout.write("\n");
    if (listMigrationDirectoriesResult.migrations.length > 0) {
      const migrations = listMigrationDirectoriesResult.migrations;
      process.stdout.write(
        `${migrations.length} migration${migrations.length > 1 ? "s" : ""} found in prisma/migrations
`
      );
    } else {
      process.stdout.write(`No migration found in prisma/migrations
`);
    }
    let unappliedMigrations = [];
    if (diagnoseResult.history?.diagnostic === "databaseIsBehind") {
      unappliedMigrations = diagnoseResult.history.unappliedMigrationNames;
      process.stdout.write(
        `Following migration${unappliedMigrations.length > 1 ? "s" : ""} have not yet been applied:
${unappliedMigrations.join("\n")}

To apply migrations in development run ${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate dev`)))}.
To apply migrations in production run ${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate deploy`)))}.
`
      );
      process.exit(1);
    } else if (diagnoseResult.history?.diagnostic === "historiesDiverge") {
      console.error(`Your local migration history and the migrations table from your database are different:

The last common migration is: ${diagnoseResult.history.lastCommonMigrationName}

The migration${diagnoseResult.history.unappliedMigrationNames.length > 1 ? "s" : ""} have not yet been applied:
${diagnoseResult.history.unappliedMigrationNames.join("\n")}

The migration${diagnoseResult.history.unpersistedMigrationNames.length > 1 ? "s" : ""} from the database are not found locally in prisma/migrations:
${diagnoseResult.history.unpersistedMigrationNames.join("\n")}`);
      process.exit(1);
    }
    if (!diagnoseResult.hasMigrationsTable) {
      if (listMigrationDirectoriesResult.migrations.length === 0) {
        console.error(`The current database is not managed by Prisma Migrate.

Read more about how to baseline an existing production database:
${(0, import_internals.link)("https://pris.ly/d/migrate-baseline")}`);
        process.exit(1);
      } else {
        const migrationId = listMigrationDirectoriesResult.migrations.shift();
        console.error(`The current database is not managed by Prisma Migrate.

If you want to keep the current database structure and data and create new migrations, baseline this database with the migration "${migrationId}":
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate resolve --applied "${migrationId}"`)))}

Read more about how to baseline an existing production database:
https://pris.ly/d/migrate-baseline`);
        process.exit(1);
      }
    } else if (diagnoseResult.failedMigrationNames.length > 0) {
      const failedMigrations = diagnoseResult.failedMigrationNames;
      console.error(
        `Following migration${failedMigrations.length > 1 ? "s" : ""} have failed:
${failedMigrations.join("\n")}

During development if the failed migration(s) have not been deployed to a production database you can then fix the migration(s) and run ${(0, import_chunk_SKRR5WT4.bold)(
          (0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate dev`))
        )}.
`
      );
      console.error(`The failed migration(s) can be marked as rolled back or applied:

- If you rolled back the migration(s) manually:
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate resolve --rolled-back "${failedMigrations[0]}"`)))}

- If you fixed the database manually (hotfix):
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)(`prisma migrate resolve --applied "${failedMigrations[0]}"`)))}

Read more about how to resolve migration issues in a production database:
${(0, import_internals.link)("https://pris.ly/d/migrate-resolve")}`);
      process.exit(1);
    } else {
      process.stdout.write("\n");
      if (unappliedMigrations.length === 0) {
        return `Database schema is up to date!`;
      }
    }
    return "";
  }
  help(error) {
    if (error) {
      return new import_internals.HelpError(`
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)(`!`))} ${error}
${_MigrateStatus.help}`);
    }
    return _MigrateStatus.help;
  }
};
