#!/usr/bin/env bash
# Production-build smoke (QA_PLAN B15): builds the app, boots `node server.js`
# serving dist/ against a scratch DB, and drives the real artifact with Playwright
# to confirm the split vendor chunks load and the app works in production.
set -euo pipefail
cd "$(dirname "$0")/.."

PORT="${PROD_SMOKE_PORT:-3098}"
export PROD_SMOKE_URL="http://localhost:${PORT}"

echo "[prod-smoke] building…"
npm run build >/dev/null

echo "[prod-smoke] preparing scratch DB…"
node e2e/setup/prepare-db.js >/dev/null 2>&1

echo "[prod-smoke] starting production server on :${PORT}…"
DB_PATH="db/e2e.db" PORT="${PORT}" BIND_HOST=127.0.0.1 node server.js >/tmp/prod-smoke-server.log 2>&1 &
SRV=$!
trap 'kill "${SRV}" 2>/dev/null || true' EXIT

for _ in $(seq 1 40); do
  curl -sf "http://localhost:${PORT}/api/version" >/dev/null 2>&1 && break
  sleep 0.5
done

node scripts/prod-smoke.js
