"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_AIIYWKAA_exports = {};
__export(chunk_AIIYWKAA_exports, {
  MigrateDev: () => MigrateDev,
  init_MigrateDev: () => init_MigrateDev
});
module.exports = __toCommonJS(chunk_AIIYWKAA_exports);
var import_chunk_P7JG3R4L = require("./chunk-P7JG3R4L.js");
var import_chunk_NM62A4NV = require("./chunk-NM62A4NV.js");
var import_chunk_VHXQHY5M = require("./chunk-VHXQHY5M.js");
var import_chunk_YUDCPOWB = require("./chunk-YUDCPOWB.js");
var import_chunk_4O5LXQ62 = require("./chunk-4O5LXQ62.js");
var import_chunk_BOP7PHOB = require("./chunk-BOP7PHOB.js");
var import_chunk_KCMQOXUX = require("./chunk-KCMQOXUX.js");
var import_chunk_FFLD75KX = require("./chunk-FFLD75KX.js");
var import_chunk_PZ4BRULM = require("./chunk-PZ4BRULM.js");
var import_chunk_2CL32XWS = require("./chunk-2CL32XWS.js");
var import_chunk_F7KSWWYN = require("./chunk-F7KSWWYN.js");
var import_chunk_FVJ3R4NJ = require("./chunk-FVJ3R4NJ.js");
var import_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var import_fs = __toESM(require("fs"));
var import_prompts = __toESM(require("prompts"));
var debug, _MigrateDev, MigrateDev;
var init_MigrateDev = (0, import_chunk_FVJ3R4NJ.__esm)({
  "src/commands/MigrateDev.ts"() {
    (0, import_chunk_F7KSWWYN.init_colors)();
    (0, import_chunk_BOP7PHOB.init_Migrate)();
    (0, import_chunk_PZ4BRULM.init_ensureDatabaseExists)();
    (0, import_chunk_2CL32XWS.init_errors)();
    (0, import_chunk_KCMQOXUX.init_getSchemaPathAndPrint)();
    (0, import_chunk_NM62A4NV.init_handleEvaluateDataloss)();
    (0, import_chunk_FFLD75KX.init_printDatasource)();
    (0, import_chunk_YUDCPOWB.init_printFiles)();
    (0, import_chunk_4O5LXQ62.init_printMigrationId)();
    (0, import_chunk_P7JG3R4L.init_promptForMigrationName)();
    (0, import_chunk_VHXQHY5M.init_seed)();
    debug = (0, import_debug.default)("prisma:migrate:dev");
    _MigrateDev = class _MigrateDev2 {
      static new() {
        return new _MigrateDev2();
      }
      async parse(argv) {
        const args = (0, import_internals.arg)(argv, {
          "--help": Boolean,
          "-h": "--help",
          "--name": String,
          "-n": "--name",
          // '--force': Boolean,
          // '-f': '--force',
          "--create-only": Boolean,
          "--schema": String,
          "--skip-generate": Boolean,
          "--skip-seed": Boolean,
          "--telemetry-information": String
        });
        if ((0, import_internals.isError)(args)) {
          return this.help(args.message);
        }
        await (0, import_internals.checkUnsupportedDataProxy)("migrate dev", args, true);
        if (args["--help"]) {
          return this.help();
        }
        (0, import_internals.loadEnvFile)({ schemaPath: args["--schema"], printMessage: true });
        const schemaPath = await (0, import_chunk_KCMQOXUX.getSchemaPathAndPrint)(args["--schema"]);
        const datasourceInfo = await (0, import_chunk_PZ4BRULM.getDatasourceInfo)({ schemaPath });
        (0, import_chunk_FFLD75KX.printDatasource)({ datasourceInfo });
        console.info();
        const schema = import_fs.default.readFileSync(schemaPath, "utf-8");
        (0, import_internals.validate)({
          datamodel: schema
        });
        await (0, import_internals.getConfig)({
          datamodel: schema,
          ignoreEnvVarErrors: false
        });
        const wasDbCreated = await (0, import_chunk_PZ4BRULM.ensureDatabaseExists)("create", schemaPath);
        if (wasDbCreated) {
          console.info(wasDbCreated);
          console.info();
        }
        const migrate = new import_chunk_BOP7PHOB.Migrate(schemaPath);
        let devDiagnostic;
        try {
          devDiagnostic = await migrate.devDiagnostic();
          debug({ devDiagnostic: JSON.stringify(devDiagnostic, null, 2) });
        } catch (e) {
          migrate.stop();
          throw e;
        }
        const migrationIdsApplied = [];
        if (devDiagnostic.action.tag === "reset") {
          if (!args["--force"]) {
            if (!(0, import_internals.canPrompt)()) {
              migrate.stop();
              throw new import_chunk_2CL32XWS.MigrateDevEnvNonInteractiveError();
            }
            const confirmedReset = await this.confirmReset({
              datasourceInfo,
              reason: devDiagnostic.action.reason
            });
            console.info();
            if (!confirmedReset) {
              console.info("Reset cancelled.");
              migrate.stop();
              process.exit(130);
            }
          }
          try {
            await migrate.reset();
          } catch (e) {
            migrate.stop();
            throw e;
          }
        }
        try {
          const { appliedMigrationNames } = await migrate.applyMigrations();
          migrationIdsApplied.push(...appliedMigrationNames);
          if (appliedMigrationNames.length > 0) {
            console.info();
            console.info(
              `The following migration(s) have been applied:

${(0, import_chunk_YUDCPOWB.printFilesFromMigrationIds)(
                "migrations",
                appliedMigrationNames,
                {
                  "migration.sql": ""
                }
              )}`
            );
          }
        } catch (e) {
          migrate.stop();
          throw e;
        }
        let evaluateDataLossResult;
        try {
          evaluateDataLossResult = await migrate.evaluateDataLoss();
          debug({ evaluateDataLossResult });
        } catch (e) {
          migrate.stop();
          throw e;
        }
        const unexecutableStepsError = (0, import_chunk_NM62A4NV.handleUnexecutableSteps)(
          evaluateDataLossResult.unexecutableSteps,
          args["--create-only"]
        );
        if (unexecutableStepsError) {
          migrate.stop();
          throw new Error(unexecutableStepsError);
        }
        if (evaluateDataLossResult.warnings && evaluateDataLossResult.warnings.length > 0) {
          console.log((0, import_chunk_F7KSWWYN.bold)(`
\u26A0\uFE0F  Warnings for the current datasource:
`));
          for (const warning of evaluateDataLossResult.warnings) {
            console.log(`  \u2022 ${warning.message}`);
          }
          console.info();
          if (!args["--force"]) {
            if (!(0, import_internals.canPrompt)()) {
              migrate.stop();
              throw new import_chunk_2CL32XWS.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) {
              console.info("Migration cancelled.");
              migrate.stop();
              process.exit(130);
            }
          }
        }
        let migrationName = void 0;
        if (evaluateDataLossResult.migrationSteps > 0 || args["--create-only"]) {
          const getMigrationNameResult = await (0, import_chunk_P7JG3R4L.getMigrationName)(args["--name"]);
          if (getMigrationNameResult.userCancelled) {
            console.log(getMigrationNameResult.userCancelled);
            migrate.stop();
            process.exit(130);
          } else {
            migrationName = getMigrationNameResult.name;
          }
        }
        let migrationIds;
        try {
          const createMigrationResult = await migrate.createMigration({
            migrationsDirectoryPath: migrate.migrationsDirectoryPath,
            migrationName: migrationName || "",
            draft: args["--create-only"] ? true : false,
            prismaSchema: migrate.getPrismaSchema()
          });
          debug({ createMigrationResult });
          if (args["--create-only"]) {
            migrate.stop();
            return `Prisma Migrate created the following migration without applying it ${(0, import_chunk_4O5LXQ62.printMigrationId)(
              createMigrationResult.generatedMigrationName
            )}

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

${(0, import_chunk_YUDCPOWB.printFilesFromMigrationIds)(
              "migrations",
              migrationIds,
              {
                "migration.sql": ""
              }
            )}

${(0, import_chunk_F7KSWWYN.green)("Your database is now in sync with your schema.")}`
          );
        }
        if (!process.env.PRISMA_MIGRATE_SKIP_GENERATE && !args["--skip-generate"]) {
          await migrate.tryToRunGenerate();
          console.info();
        }
        if ((wasDbCreated || devDiagnostic.action.tag === "reset") && !process.env.PRISMA_MIGRATE_SKIP_SEED && !args["--skip-seed"]) {
          try {
            const seedCommandFromPkgJson = await (0, import_chunk_VHXQHY5M.getSeedCommandFromPackageJson)(process.cwd());
            if (seedCommandFromPkgJson) {
              console.info();
              const successfulSeeding = await (0, import_chunk_VHXQHY5M.executeSeedCommand)({ commandFromConfig: seedCommandFromPkgJson });
              if (successfulSeeding) {
                console.info(`
${process.platform === "win32" ? "" : "\u{1F331}  "}The seed command has been executed.
`);
              } else {
                process.exit(1);
              }
            } else {
              const schemaPath2 = await (0, import_internals.getSchemaPath)(args["--schema"]);
              await (0, import_chunk_VHXQHY5M.verifySeedConfigAndReturnMessage)(schemaPath2);
            }
          } catch (e) {
            console.error(e);
          }
        }
        return "";
      }
      async confirmReset({
        datasourceInfo,
        reason
      }) {
        console.info(reason);
        let messageFirstLine = "";
        if (["PostgreSQL", "SQL Server"].includes(datasourceInfo.prettyProvider)) {
          if (datasourceInfo.schemas?.length) {
            messageFirstLine = `We need to reset the following schemas: "${datasourceInfo.schemas.join(", ")}"`;
          } else if (datasourceInfo.schema) {
            messageFirstLine = `We need to reset the "${datasourceInfo.schema}" schema`;
          } else {
            messageFirstLine = `We need to reset the database schema`;
          }
        } else {
          messageFirstLine = `We need to reset the ${datasourceInfo.prettyProvider} database "${datasourceInfo.dbName}"`;
        }
        if (datasourceInfo.dbLocation) {
          messageFirstLine += ` at "${datasourceInfo.dbLocation}"`;
        }
        const messageForPrompt = `${messageFirstLine}
Do you want to continue? ${(0, import_chunk_F7KSWWYN.red)("All data will be lost")}.`;
        if (Boolean(import_prompts.default._injected?.length) === true) {
          console.info(messageForPrompt);
        }
        const confirmation = await (0, import_prompts.default)({
          type: "confirm",
          name: "value",
          message: messageForPrompt
        });
        return confirmation.value;
      }
      help(error) {
        if (error) {
          return new import_internals.HelpError(`
${(0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.red)(`!`))} ${error}
${_MigrateDev2.help}`);
        }
        return _MigrateDev2.help;
      }
    };
    _MigrateDev.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_F7KSWWYN.bold)("Usage")}

  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma migrate dev [options]

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

       -h, --help   Display this help message
         --schema   Custom path to your Prisma schema
       -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
  --skip-generate   Skip triggering generators (e.g. Prisma Client)
      --skip-seed   Skip triggering seed

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

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

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

  Create a migration without applying it
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma migrate dev --create-only
  `);
    MigrateDev = _MigrateDev;
  }
});
