"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_KPQKIXQM_exports = {};
__export(chunk_KPQKIXQM_exports, {
  DbPush: () => DbPush
});
module.exports = __toCommonJS(chunk_KPQKIXQM_exports);
var import_chunk_FBDQVK4W = require("./chunk-FBDQVK4W.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_internals = require("@prisma/internals");
var import_prompts = __toESM(require("prompts"));
var DbPush = class _DbPush {
  static new() {
    return new _DbPush();
  }
  static help = (0, import_internals.format)(`
${process.platform === "win32" ? "" : "\u{1F64C}  "}Push the state from your Prisma schema to your database

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

  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db push [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
   --accept-data-loss   Ignore data loss warnings
        --force-reset   Force a reset of the database before push

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

  Push the Prisma schema state to the database
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db push

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

  Ignore data loss warnings
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db push --accept-data-loss
`);
  async parse(argv, config, baseDir) {
    const args = (0, import_internals.arg)(
      argv,
      {
        "--help": Boolean,
        "-h": "--help",
        "--accept-data-loss": Boolean,
        "--force-reset": Boolean,
        "--schema": String,
        "--config": String,
        "--url": 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);
    let cmdSpecificConfig = config;
    if (args["--url"]) {
      cmdSpecificConfig = {
        ...cmdSpecificConfig,
        datasource: {
          ...cmdSpecificConfig.datasource,
          url: args["--url"]
        }
      };
    }
    const cmd = "db push";
    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 });
    const schemaFilter = {
      externalTables: cmdSpecificConfig.tables?.external ?? [],
      externalEnums: cmdSpecificConfig.enums?.external ?? []
    };
    const migrate = await import_chunk_RGXJYLMD.Migrate.setup({
      schemaEngineConfig: cmdSpecificConfig,
      baseDir,
      migrationsDirPath,
      schemaContext,
      schemaFilter,
      extensions: cmdSpecificConfig["extensions"]
    });
    try {
      const successMessage = await (0, import_chunk_BRPS327A.ensureDatabaseExists)(
        baseDir,
        (0, import_internals.getSchemaDatasourceProvider)(schemaContext),
        validatedConfig
      );
      if (successMessage) {
        process.stdout.write("\n" + successMessage + "\n");
      }
    } catch (e) {
      process.stdout.write("\n");
      throw e;
    }
    let wasDatabaseReset = false;
    if (args["--force-reset"]) {
      process.stdout.write("\n");
      (0, import_chunk_FBDQVK4W.aiAgentConfirmationCheckpoint)();
      try {
        await migrate.reset();
      } catch (e) {
        await migrate.stop();
        throw e;
      }
      let successfulResetMsg = `The ${datasourceInfo.prettyProvider} database`;
      if (datasourceInfo.dbName) {
        successfulResetMsg += ` "${datasourceInfo.dbName}"`;
      }
      const schemasLength = datasourceInfo.schemas?.length || 0;
      if (datasourceInfo.schemas && schemasLength > 0) {
        successfulResetMsg += ` schema${schemasLength > 1 ? "s" : ""} "${datasourceInfo.schemas.join(", ")}"`;
      } else if (datasourceInfo.schema) {
        successfulResetMsg += ` schema "${datasourceInfo.schema}"`;
      }
      if (datasourceInfo.dbLocation) {
        successfulResetMsg += ` at "${datasourceInfo.dbLocation}"`;
      }
      successfulResetMsg += ` ${schemasLength > 1 ? "were" : "was"} successfully reset.
`;
      process.stdout.write(successfulResetMsg);
      wasDatabaseReset = true;
    }
    const before = Math.round(performance.now());
    let migration;
    try {
      migration = await migrate.push({
        force: args["--accept-data-loss"]
      });
    } catch (e) {
      await migrate.stop();
      throw e;
    }
    if (migration.unexecutable && migration.unexecutable.length > 0) {
      const messages = [];
      messages.push(`${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)("\n\u26A0\uFE0F We found changes that cannot be executed:\n"))}`);
      for (const item of migration.unexecutable) {
        messages.push(`  \u2022 ${item}`);
      }
      process.stdout.write("\n");
      await migrate.stop();
      throw new Error(`${messages.join("\n")}

You may use the --force-reset flag to drop the database before push like ${(0, import_chunk_SKRR5WT4.bold)(
        (0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma db push --force-reset"))
      )}
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)("All data will be lost."))}
      `);
    }
    if (migration.warnings && migration.warnings.length > 0) {
      process.stdout.write((0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.yellow)(`
\u26A0\uFE0F  There might be data loss when applying the changes:

`)));
      for (const warning of migration.warnings) {
        process.stdout.write(`  \u2022 ${warning}

`);
      }
      process.stdout.write("\n");
      if (!args["--accept-data-loss"]) {
        if (!(0, import_internals.canPrompt)()) {
          await migrate.stop();
          throw new import_chunk_ZUHJASAP.DbPushIgnoreWarningsWithFlagError();
        }
        process.stdout.write("\n");
        const confirmation = await (0, import_prompts.default)({
          type: "confirm",
          name: "value",
          message: `Do you want to ignore the warning(s)?`
        });
        if (!confirmation.value) {
          process.stdout.write("Push cancelled.\n");
          await migrate.stop();
          process.exit(130);
        }
        try {
          await migrate.push({
            force: true
          });
        } catch (e) {
          await migrate.stop();
          throw e;
        }
      }
    }
    await migrate.stop();
    if (!wasDatabaseReset && migration.warnings.length === 0 && migration.executedSteps === 0) {
      process.stdout.write(`
The database is already in sync with the Prisma schema.
`);
    } else {
      const migrationTimeMessage = `Done in ${(0, import_internals.formatms)(Math.round(performance.now()) - before)}`;
      const rocketEmoji = process.platform === "win32" ? "" : "\u{1F680}  ";
      const migrationSuccessStdMessage = "Your database is now in sync with your Prisma schema.";
      const migrationSuccessMongoMessage = "Your database indexes are now in sync with your Prisma schema.";
      const provider = schemaContext.primaryDatasource?.activeProvider;
      process.stdout.write(
        `
${rocketEmoji}${provider === "mongodb" ? migrationSuccessMongoMessage : migrationSuccessStdMessage} ${migrationTimeMessage}
`
      );
    }
    return ``;
  }
  help(error) {
    if (error) {
      return new import_internals.HelpError(`
${(0, import_chunk_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)(`!`))} ${error}
${_DbPush.help}`);
    }
    return _DbPush.help;
  }
};
