import { spawn } from "node:child_process";

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

if (args.length === 0) {
  console.error("Usage: node scripts/with-db-url.mjs <command> [...args]");
  process.exit(1);
}

const buildDatabaseUrl = () => {
  const host = process.env.CHAT_POSTGRES_HOST?.trim() || "localhost";
  const port = process.env.CHAT_POSTGRES_PORT?.trim() || "5432";
  const database = process.env.CHAT_POSTGRES_DB?.trim();
  const user = process.env.CHAT_POSTGRES_USER?.trim();
  const password = process.env.CHAT_POSTGRES_PASSWORD ?? "";
  const schema = process.env.CHAT_POSTGRES_SCHEMA?.trim() || "public";

  if (database && user) {
    const credentials = `${encodeURIComponent(user)}:${encodeURIComponent(password)}@`;
    return `postgresql://${credentials}${host}:${port}/${database}?schema=${encodeURIComponent(schema)}`;
  }

  const explicitUrl = process.env.CHAT_DATABASE_URL?.trim();
  if (explicitUrl) {
    return explicitUrl;
  }

  throw new Error("CHAT_DATABASE_URL is missing and CHAT_POSTGRES_DB/CHAT_POSTGRES_USER are not fully configured");
};

try {
  process.env.CHAT_DATABASE_URL = buildDatabaseUrl();
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
}

const child = spawn(args[0], args.slice(1), {
  stdio: "inherit",
  shell: true,
  env: process.env
});

child.on("exit", (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal);
    return;
  }

  process.exit(code ?? 1);
});
