#!/usr/bin/env node

import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
import { loadWorkspaceEnv } from "./load-env.mjs";

loadWorkspaceEnv();

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")];

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

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

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