#!/usr/bin/env node

import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
import { getExpectedDatabaseName, inspectDatabaseUrl, shouldGuardPrismaCommand } from "./db-target-guard.mjs";
import { loadWorkspaceEnv, resolveRealWorkspaceRoot } from "./load-env.mjs";

loadWorkspaceEnv();
const workspaceRoot = resolveRealWorkspaceRoot();
process.chdir(workspaceRoot);

const args = process.argv.slice(2);

if (args.length === 0) {
  console.error("Usage: node scripts/prisma-with-env.mjs <prisma-args...>");
  process.exit(1);
}

const hasSchemaArg = args.some((arg) => arg === "--schema" || arg.startsWith("--schema="));
const prismaArgs = hasSchemaArg
  ? args
  : [...args, "--schema", resolve("packages/db/prisma/schema.prisma")];

if (shouldGuardPrismaCommand(prismaArgs)) {
  try {
    inspectDatabaseUrl(process.env.DATABASE_URL, getExpectedDatabaseName());
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    console.error("Refusing to run Prisma against an unexpected database target.");
    console.error("Use the repo env files for CapaKraken, or set CAPAKRAKEN_EXPECTED_DB_NAME explicitly if you intentionally target another database.");
    process.exit(1);
  }
}

const result = spawnSync("pnpm", ["--filter", "@capakraken/db", "exec", "prisma", ...prismaArgs], {
  stdio: "inherit",
  env: process.env,
  cwd: workspaceRoot,
});

if (result.error) {
  console.error(result.error.message);
  process.exit(1);
}

process.exit(result.status ?? 1);
