const { spawn } = require('child_process');

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

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

function buildDatabaseUrl() {
  const host = (process.env.POSTGRES_HOST || 'localhost').trim();
  const port = (process.env.POSTGRES_PORT || '5432').trim();
  const database = process.env.POSTGRES_DB && process.env.POSTGRES_DB.trim();
  const user = process.env.POSTGRES_USER && process.env.POSTGRES_USER.trim();
  const password = process.env.POSTGRES_PASSWORD || '';
  const schema = (process.env.POSTGRES_SCHEMA || 'public').trim();

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

  const explicitUrl = process.env.DATABASE_URL && process.env.DATABASE_URL.trim();
  if (explicitUrl) {
    return explicitUrl;
  }

  throw new Error('DATABASE_URL is missing and POSTGRES_DB/POSTGRES_USER are not fully configured');
}

try {
  process.env.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 == null ? 1 : code);
});
