import {
  assertDestructiveDbAllowed,
  formatTarget,
  parseDatabaseUrl,
} from "./destructive-db-guard.js";

const TEST_DATABASE_NAMES = ["nexus_test", "nexus_e2e", "nexus_ci"];

export function assertSafeSeedTarget(commandName: string) {
  return assertDestructiveDbAllowed({
    commandName,
    allowedDatabaseNames: TEST_DATABASE_NAMES,
  });
}

export function assertNexusDbTarget(commandName: string) {
  const rawUrl = process.env.DATABASE_URL;

  if (!rawUrl) {
    throw new Error(
      `${commandName} aborted: DATABASE_URL is not configured. Run the command through the Nexus env wrappers so the workspace env files are loaded.`,
    );
  }

  const target = parseDatabaseUrl(rawUrl);

  if (!target.databaseName.startsWith("nexus")) {
    throw new Error(
      `${commandName} aborted: database '${target.databaseName}' is not a valid Nexus target. Target=${formatTarget(target)}`,
    );
  }

  return target;
}
