#!/usr/bin/env bash
# Den production deploy. Idempotent — safe to re-run by hand or from CI.
# Called automatically by .github/workflows/deploy.yml on push to main.
#
# Uses `npm ci` (not `npm install`) so package-lock.json never drifts.
# The workflow does its own git fetch + reset --hard before invoking
# this script, so we don't repeat that here.

set -euo pipefail

REPO_ROOT="/var/www/den.fearthewild.com"
HEALTH_URL="https://den.fearthewild.com/api/health"

cd "$REPO_ROOT"

echo "→ api: clean install + build"
cd api
npm ci
npm run build

echo "→ restart den-api"
systemctl restart den-api

echo "→ web: clean install + build"
cd ../web
npm ci
npm run build

echo "→ verify health"
sleep 2
if ! curl -sf "$HEALTH_URL" | grep -q '"ok":true'; then
  echo "ERROR: health check failed!" >&2
  exit 1
fi

echo "✓ Deploy complete"
