#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${POST_DEPLOY_BASE_URL:-${PLAYWRIGHT_BASE_URL:-http://127.0.0.1:8000}}"
BASE_URL="${BASE_URL%/}"

echo "Post-deploy health gate for ${BASE_URL}"

failures=0

check_endpoint() {
  local name="$1"
  local path="$2"
  local url="${BASE_URL}${path}"

  if ! response="$(curl -fsS "$url")"; then
    echo "[FAIL] ${name} — request failed (${url})"
    failures=$((failures + 1))
    return
  fi

  local status
  status="$(printf '%s' "$response" | php -r '$d=json_decode(stream_get_contents(STDIN), true); echo $d["status"] ?? "unknown";')"

  if [[ "$status" == "error" ]]; then
    echo "[FAIL] ${name} — status=error"
    failures=$((failures + 1))
  else
    echo "[OK] ${name} — status=${status}"
  fi
}

check_endpoint "aggregate" "/health"
check_endpoint "database" "/health/database"
check_endpoint "cache" "/health/cache"
check_endpoint "queue" "/health/queue"
check_endpoint "mail" "/health/mail"
check_endpoint "storage" "/health/storage"
check_endpoint "reverb" "/health/reverb"

if command -v php >/dev/null 2>&1 && [[ -f artisan ]]; then
  echo "Running php artisan mvhelpdesk:ops-check"
  if ! php artisan mvhelpdesk:ops-check --json >/tmp/mvhelpdesk-ops-check.json; then
    echo "[FAIL] mvhelpdesk:ops-check"
    failures=$((failures + 1))
  else
    echo "[OK] mvhelpdesk:ops-check"
  fi
fi

if [[ "$failures" -gt 0 ]]; then
  echo "Post-deploy health gate failed with ${failures} issue(s)."
  exit 1
fi

echo "Post-deploy health gate passed."
