"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_6UO6YJTU_exports = {};
__export(chunk_6UO6YJTU_exports, {
  MigrateDev: () => MigrateDev
});
module.exports = __toCommonJS(chunk_6UO6YJTU_exports);
var import_chunk_C3722PDA = require("./chunk-C3722PDA.js");
var import_chunk_7CQBDP4H = require("./chunk-7CQBDP4H.js");
var import_chunk_KRQEFTDT = require("./chunk-KRQEFTDT.js");
var import_chunk_UP6FVCDK = require("./chunk-UP6FVCDK.js");
var import_chunk_ZUHJASAP = require("./chunk-ZUHJASAP.js");
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_node_path = __toESM(require("node:path"));
var import_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var import_prompts = __toESM(require("prompts"));
var debug = (0, import_debug.default)("prisma:migrate:dev");
var MigrateDev = class _MigrateDev {
  static new() {
    return new _MigrateDev();
  }
  static help = (0, import_internals.format)(`
${process.platform === "win32" ? "" : "\u{1F3CB}\uFE0F  "}Create a migration from changes in Prisma schema, apply it to the database, trigger generators (e.g. Prisma Client)

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

  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate dev [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
         --url      Override the datasource URL from the Prisma config file
       -n, --name   Name the migration
    --create-only   Create a new migration but do not apply it
                    The migration will be empty if there are no changes in Prisma schema

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

  Create a migration from changes in Prisma schema, apply it to the database, trigger generators (e.g. Prisma Client)
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate dev

  Specify a schema
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate dev --schema=./schema.prisma

  Create a migration without applying it
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma migrate dev --create-only
  `);
  async parse(argv, config, baseDir) {
    const args = (0, import_internals.arg)(argv, {
      "--help": Boolean,
      "-h": "--help",
      "--name": String,
      "-n": "--name",
      // '--force': Boolean,
      // '-f': '--force',
      "--create-only": Boolean,
      "--schema": String,
      "--config": String,
      "--url": String,
      "--telemetry-information": String
    });
    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);
    let cmdSpecificConfig = config;
    if (args["--url"]) {
      cmdSpecificConfig = {
        ...cmdSpecificConfig,
        datasource: {
          ...cmdSpecificConfig.datasource,
          url: args["--url"]
        }
      };
    }
    const cmd = "migrate dev";
    const validatedConfig = (0, import_internals.validatePrismaConfigWithDatasource)({ config: cmdSpecificConfig, cmd });
    (0, import_internals.checkUnsupportedDataProxy)({ cmd, validatedConfig });
    const datasourceInfo = (0, import_chunk_BRPS327A.parseDatasourceInfo)(schemaContext.primaryDatasource, validatedConfig);
    (0, import_chunk_QOPTDDIH.printDatasource)({ datasourceInfo });
    process.stdout.write("\n");
    (0, import_internals.validate)({ schemas: schemaContext.schemaFiles });
    const successMessage = await (0, import_chunk_BRPS327A.ensureDatabaseExists)(
      baseDir,
      (0, import_internals.getSchemaDatasourceProvider)(schemaContext),
      validatedConfig
    );
    if (successMessage) {
      process.stdout.write(successMessage + "\n\n");
    }
    const schemaFilter = {
      externalTables: cmdSpecificConfig.tables?.external ?? [],
      externalEnums: cmdSpecificConfig.enums?.external ?? []
    };
    const migrate = await import_chunk_RGXJYLMD.Migrate.setup({
      schemaEngineConfig: cmdSpecificConfig,
      baseDir,
      migrationsDirPath,
      schemaContext,
      schemaFilter,
      shadowDbInitScript: cmdSpecificConfig.migrations?.initShadowDb,
      extensions: cmdSpecificConfig["extensions"]
    });
    let devDiagnostic;
    try {
      devDiagnostic = await migrate.devDiagnostic();
      debug({ devDiagnostic: JSON.stringify(devDiagnostic, null, 2) });
    } catch (e) {
      await migrate.stop();
      throw e;
    }
    const migrationIdsApplied = [];
    if (devDiagnostic.action.tag === "reset") {
      this.logResetReason({
        datasourceInfo,
        reason: devDiagnostic.action.reason
      });
      process.stdout.write(
        `
You may use ${(0, import_chunk_SKRR5WT4.red)("prisma migrate reset")} to drop the development database.
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)("All data will be lost."))}
`
      );
      await migrate.stop();
      process.exit(130);
    }
    try {
      const { appliedMigrationNames } = await migrate.applyMigrations();
      migrationIdsApplied.push(...appliedMigrationNames);
      if (appliedMigrationNames.length > 0) {
        process.stdout.write(
          `
The following migration(s) have been applied:

${(0, import_chunk_KRQEFTDT.printFilesFromMigrationIds)(
            "migrations",
            appliedMigrationNames,
            {
              "migration.sql": ""
            }
          )}
`
        );
      }
    } catch (e) {
      await migrate.stop();
      throw e;
    }
    let evaluateDataLossResult;
    try {
      evaluateDataLossResult = await migrate.evaluateDataLoss();
      debug({ evaluateDataLossResult });
    } catch (e) {
      await migrate.stop();
      throw e;
    }
    const unexecutableStepsError = (0, import_chunk_7CQBDP4H.handleUnexecutableSteps)(
      evaluateDataLossResult.unexecutableSteps,
      args["--create-only"]
    );
    if (unexecutableStepsError) {
      await migrate.stop();
      throw new Error(unexecutableStepsError);
    }
    if (evaluateDataLossResult.warnings && evaluateDataLossResult.warnings.length > 0) {
      process.stdout.write((0, import_chunk_SKRR5WT4.bold)(`
\u26A0\uFE0F  Warnings for the current datasource:

`));
      for (const warning of evaluateDataLossResult.warnings) {
        process.stdout.write(`  \u2022 ${warning.message}
`);
      }
      process.stdout.write("\n");
      if (!args["--force"]) {
        if (!(0, import_internals.canPrompt)()) {
          await migrate.stop();
          throw new import_chunk_ZUHJASAP.MigrateDevEnvNonInteractiveError();
        }
        const message = args["--create-only"] ? "Are you sure you want to create this migration?" : "Are you sure you want to create and apply this migration?";
        const confirmation = await (0, import_prompts.default)({
          type: "confirm",
          name: "value",
          message
        });
        if (!confirmation.value) {
          process.stdout.write("Migration cancelled.\n");
          await migrate.stop();
          process.exit(130);
        }
      }
    }
    let migrationName = void 0;
    if (evaluateDataLossResult.migrationSteps > 0 || args["--create-only"]) {
      const getMigrationNameResult = await (0, import_chunk_C3722PDA.getMigrationName)(args["--name"]);
      if (getMigrationNameResult.userCancelled) {
        process.stdout.write(getMigrationNameResult.userCancelled + "\n");
        await migrate.stop();
        process.exit(130);
      } else {
        migrationName = getMigrationNameResult.name;
      }
    }
    let migrationIds;
    try {
      const createMigrationResult = await migrate.createMigration({
        migrationName: migrationName || "",
        draft: args["--create-only"] ? true : false,
        schema: migrate.getPrismaSchema()
      });
      debug({ createMigrationResult });
      if (args["--create-only"]) {
        await migrate.stop();
        return `Prisma Migrate created the following migration without applying it ${(0, import_chunk_UP6FVCDK.printMigrationId)(
          createMigrationResult.generatedMigrationName
        )}

You can now edit it and apply it by running ${(0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma migrate dev"))}.`;
      }
      const { appliedMigrationNames } = await migrate.applyMigrations();
      migrationIds = appliedMigrationNames;
    } finally {
      await migrate.stop();
    }
    migrationIdsApplied.length > 0 && process.stdout.write("\n");
    if (migrationIds.length === 0) {
      if (migrationIdsApplied.length > 0) {
        process.stdout.write(`${(0, import_chunk_SKRR5WT4.green)("Your database is now in sync with your schema.")}
`);
      } else {
        process.stdout.write(`Already in sync, no schema change or pending migration was found.
`);
      }
    } else {
      const migrationsDirPathRelative = import_node_path.default.relative(process.cwd(), migrationsDirPath);
      process.stdout.write(
        `
The following migration(s) have been created and applied from new schema changes:

${(0, import_chunk_KRQEFTDT.printFilesFromMigrationIds)(
          migrationsDirPathRelative,
          migrationIds,
          {
            "migration.sql": ""
          }
        )}

${(0, import_chunk_SKRR5WT4.green)("Your database is now in sync with your schema.")}
`
      );
    }
    return "";
  }
  logResetReason({ datasourceInfo, reason }) {
    process.stdout.write(reason + "\n");
    let message;
    if (["PostgreSQL", "SQL Server"].includes(datasourceInfo.prettyProvider)) {
      if (datasourceInfo.schemas?.length) {
        message = `We need to reset the following schemas: "${datasourceInfo.schemas.join(", ")}"`;
      } else if (datasourceInfo.schema) {
        message = `We need to reset the "${datasourceInfo.schema}" schema`;
      } else {
        message = `We need to reset the database schema`;
      }
    } else {
      message = `We need to reset the ${datasourceInfo.prettyProvider} database "${datasourceInfo.dbName}"`;
    }
    if (datasourceInfo.dbLocation) {
      message += ` at "${datasourceInfo.dbLocation}"`;
    }
    process.stdout.write(`${message}
`);
  }
  help(error) {
    if (error) {
      return new import_internals.HelpError(`
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)(`!`))} ${error}
${_MigrateDev.help}`);
    }
    return _MigrateDev.help;
  }
};
