#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
die(){ echo "PHASE 22 BLOCKED: $*" >&2; exit 1; }

echo "[1/9] Static preflight"
bash scripts/verify-project.sh

echo "[2/9] Host prerequisites"
command -v docker >/dev/null 2>&1 || die "Docker is not installed."
docker compose version >/dev/null 2>&1 || die "Docker Compose plugin is unavailable."
[[ -s composer.lock ]] || die "composer.lock is missing; generate and review it first."
[[ -f .env ]] || die ".env is missing; configure a staging-only environment."
grep -Eq '^APP_ENV=production$' .env || die "Staging container APP_ENV must be production."
grep -Eq '^APP_DEBUG=false$' .env || die "APP_DEBUG must be false."
grep -Eq '^APP_URL=https://' .env || die "APP_URL must use HTTPS."
grep -Eq '^APP_KEY=base64:.{20,}$' .env || die "APP_KEY is missing."
grep -Eq '^DB_PASSWORD=.{16,}$' .env || die "DB_PASSWORD must be at least 16 characters."
grep -Eq '^MYSQL_ROOT_PASSWORD=.{20,}$' .env || die "MYSQL_ROOT_PASSWORD must be at least 20 characters."
grep -Eq '^SESSION_SECURE_COOKIE=true$' .env || die "SESSION_SECURE_COOKIE=true is required."
grep -Eq '^SESSION_ENCRYPT=true$' .env || die "SESSION_ENCRYPT=true is required."

echo "[3/9] Validate and build production services"
docker compose config --quiet
docker compose build --pull app nginx queue scheduler

echo "[4/9] Start database and wait for health"
docker compose up -d mysql
healthy=0
for _ in $(seq 1 60); do
  status="$(docker inspect --format='{{.State.Health.Status}}' "$(docker compose ps -q mysql)" 2>/dev/null || true)"
  if [[ "$status" == "healthy" ]]; then healthy=1; break; fi
  sleep 2
done
[[ "$healthy" == "1" ]] || die "MySQL did not become healthy within 120 seconds."

echo "[5/9] Start application, web server, queue and scheduler"
docker compose up -d app nginx queue scheduler
docker compose exec -T app php artisan about
docker compose exec -T app php artisan route:list --except-vendor >/tmp/ojodu-phase22-routes.txt
[[ -s /tmp/ojodu-phase22-routes.txt ]] || die "Laravel route table is empty."

echo "[6/9] Inspect migration status"
docker compose exec -T app php artisan migrate:status
if [[ "${APPLY_MIGRATIONS:-}" == "YES" ]]; then
  echo "Applying migrations to the configured STAGING database."
  docker compose exec -T app php artisan migrate --force
else
  die "Migrations were not applied. Review the status, take a verified backup, then rerun with APPLY_MIGRATIONS=YES."
fi

echo "[7/9] Build and run isolated PHPUnit container"
docker compose --profile testing build test
docker compose --profile testing run --rm test

echo "[8/9] HTTPS staging smoke tests"
[[ -n "${HMIS_BASE_URL:-}" ]] || die "Set HMIS_BASE_URL to the HTTPS staging URL."
[[ "$HMIS_BASE_URL" == https://* ]] || die "HMIS_BASE_URL must use HTTPS."
bash scripts/http-smoke-test.sh "$HMIS_BASE_URL"

echo "[9/9] Runtime status"
docker compose ps
echo "Staging deployment and automated runtime checks completed."
echo "This is not production approval. Complete clinical, finance, privacy, security, interoperability, performance and restore acceptance separately."
