#!/usr/bin/env node
/**
 * Pre-deploy verification chain (fast defaults for CI).
 * Optional env:
 *   VERIFY_DEPLOY_MIGRATE_CHECK=true — run `npm run migrate:check` (needs SOVEREIGN_DB_CONNECTION)
 *   VERIFY_DEPLOY_LIVE_API=http://host:3041 — run smoke-verify against a running API
 *   VERIFY_DEPLOY_WEB_BUILD=true — `npm run build:web`
 */

'use strict';

const { execSync, spawnSync } = require('child_process');
const path = require('path');

const root = path.resolve(__dirname, '..');

const syntaxTargets = [
  'src/api/server.js',
  'src/api/app.js',
  'src/api/config.js',
  'src/api/lib/startupChecks.js',
  'src/api/routes/health.js',
  'src/api/scripts/migrate.js',
];

function run(cmd, opts = {}) {
  execSync(cmd, { stdio: 'inherit', cwd: root, ...opts });
}

console.log('[verify:deploy] Syntax (node --check)');for (const rel of syntaxTargets) {
  const abs = path.join(root, rel);
  const r = spawnSync(process.execPath, ['--check', abs], { stdio: 'inherit' });
  if (r.status !== 0) process.exit(r.status || 1);
}

console.log('[verify:deploy] Quality gates (route auth + feature registry)');
run('node scripts/verify-route-auth.js');
run('node scripts/verify-feature-gates.js');

console.log('[verify:deploy] API unit tests (jest)');
execSync('npm test', { stdio: 'inherit', cwd: path.join(root, 'src/api') });

const migrateCheck =
  process.env.VERIFY_DEPLOY_MIGRATE_CHECK === '1' ||
  process.env.VERIFY_DEPLOY_MIGRATE_CHECK === 'true';
if (migrateCheck) {
  console.log('[verify:deploy] SQL probe (migrate --check-only)');
  run('npm run migrate:check');
}

if (process.env.VERIFY_DEPLOY_LIVE_API) {
  console.log('[verify:deploy] Live smoke (VERIFY_DEPLOY_LIVE_API)');
  run(`node "${path.join(root, 'src/api/scripts/smoke-verify.js')}"`, {
    env: { ...process.env, API_BASE: process.env.VERIFY_DEPLOY_LIVE_API },
  });
}

const webBuild =
  process.env.VERIFY_DEPLOY_WEB_BUILD === '1' ||
  process.env.VERIFY_DEPLOY_WEB_BUILD === 'true';
if (webBuild) {
  console.log('[verify:deploy] Web production build');
  run('npm run build:web');
}

console.log('[verify:deploy] OK — pre-flight steps completed successfully');
