import { spawn } from 'node:child_process';

import { loadVaultEnvironment } from './vault/env.js';

function run(command: string, args: string[]): Promise<void> {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      env: process.env,
      stdio: 'inherit',
    });

    child.on('error', reject);
    child.on('exit', (code) => {
      if (code === 0) {
        resolve();
        return;
      }

      reject(new Error(`${command} ${args.join(' ')} exited with ${code}`));
    });
  });
}

await loadVaultEnvironment();
await run('npm', ['run', 'prisma:migrate:deploy']);
await import('./server.js');
