#!/bin/bash
# verify-deployment.sh
# Post-deployment health verification for CLI sites
#
# Usage: ./verify-deployment.sh <site-name> [base-url]
#
# Verifies:
# 1. Main page returns 200
# 2. basePath routing works
# 3. Assets load correctly
# 4. PM2 process is running (if applicable)

set -e

# Source centralized config
SCRIPT_DIR_VER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR_VER/../../scripts/config.sh"

SITE_NAME=$1
BASE_URL=${2:-"https://$WS_DOMAIN"}

if [ -z "$SITE_NAME" ]; then
  echo "Usage: $0 <site-name> [base-url]"
  echo ""
  echo "Examples:"
  echo "  $0 silicon-bali"
  echo "  $0 toumana https://example.com"
  echo "  $0 my-site http://localhost:9200"
  exit 1
fi

FULL_URL="$BASE_URL/cli/$SITE_NAME"

echo "🔍 Verifying deployment: $SITE_NAME"
echo "   URL: $FULL_URL"
echo ""

ISSUES=0
WARNINGS=0

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 1: Main Page Loads
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "1️⃣  Checking main page..."

# Try with trailing slash (trailingSlash: true)
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$FULL_URL/" 2>/dev/null || echo "000")

if [ "$STATUS" = "200" ]; then
  echo "✅ Main page loads: $FULL_URL/ (HTTP $STATUS)"
elif [ "$STATUS" = "301" ] || [ "$STATUS" = "302" ] || [ "$STATUS" = "308" ]; then
  echo "⚠️  Redirect detected: HTTP $STATUS"
  echo "   URL: $FULL_URL/"
  echo "   This might indicate a basePath configuration issue"
  WARNINGS=$((WARNINGS + 1))
elif [ "$STATUS" = "404" ]; then
  echo "❌ Page not found: HTTP 404"
  echo "   URL: $FULL_URL/"
  echo "   Check basePath configuration and nginx proxy_pass"
  ISSUES=$((ISSUES + 1))
elif [ "$STATUS" = "000" ]; then
  echo "❌ Connection failed"
  echo "   URL: $FULL_URL/"
  echo "   Check that server is running and accessible"
  ISSUES=$((ISSUES + 1))
else
  echo "❌ Unexpected status: HTTP $STATUS"
  echo "   URL: $FULL_URL/"
  ISSUES=$((ISSUES + 1))
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 2: basePath Routing
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "2️⃣  Checking basePath routing..."

# Without trailing slash (should redirect to with slash)
STATUS_NO_SLASH=$(curl -s -o /dev/null -w "%{http_code}" "$FULL_URL" -L 2>/dev/null || echo "000")

if [ "$STATUS_NO_SLASH" = "200" ]; then
  echo "✅ basePath routing works (auto-adds trailing slash)"
elif [ "$STATUS_NO_SLASH" = "301" ] || [ "$STATUS_NO_SLASH" = "308" ]; then
  # Check if redirect goes to correct place
  REDIRECT_URL=$(curl -s -o /dev/null -w "%{redirect_url}" "$FULL_URL" 2>/dev/null || echo "")
  if [ "$REDIRECT_URL" = "$FULL_URL/" ]; then
    echo "✅ basePath redirects correctly ($STATUS_NO_SLASH → $FULL_URL/)"
  else
    echo "⚠️  basePath redirect unexpected"
    echo "   Expected: $FULL_URL/"
    echo "   Got: $REDIRECT_URL"
    WARNINGS=$((WARNINGS + 1))
  fi
elif [ "$STATUS_NO_SLASH" = "404" ]; then
  echo "❌ basePath routing broken"
  echo "   URL without slash returns 404: $FULL_URL"
  echo "   Check next.config.ts basePath and trailingSlash settings"
  ISSUES=$((ISSUES + 1))
else
  echo "⚠️  Unexpected basePath behavior: HTTP $STATUS_NO_SLASH"
  WARNINGS=$((WARNINGS + 1))
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 3: Assets Load
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "3️⃣  Checking assets..."

# Download the page HTML
PAGE_HTML=$(curl -s "$FULL_URL/" 2>/dev/null || echo "")

if [ -z "$PAGE_HTML" ]; then
  echo "⏭️  Could not fetch page HTML, skipping asset checks"
else
  # Look for common Next.js assets
  if echo "$PAGE_HTML" | grep -q "_next/static"; then
    echo "✅ Next.js assets referenced in HTML"

    # Try to load a _next/static file (if we can find one)
    STATIC_FILE=$(echo "$PAGE_HTML" | grep -o "$FULL_URL/_next/static/[^\"']*" | head -1 || echo "")

    if [ -n "$STATIC_FILE" ]; then
      ASSET_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$STATIC_FILE" 2>/dev/null || echo "000")

      if [ "$ASSET_STATUS" = "200" ]; then
        echo "✅ Static assets load correctly (tested: $(basename "$STATIC_FILE"))"
      elif [ "$ASSET_STATUS" = "404" ]; then
        echo "❌ Static assets return 404"
        echo "   Tested: $STATIC_FILE"
        echo "   Check nginx location blocks and _next/static proxy"
        ISSUES=$((ISSUES + 1))
      else
        echo "⚠️  Static asset returned HTTP $ASSET_STATUS"
        WARNINGS=$((WARNINGS + 1))
      fi
    fi
  else
    echo "⚠️  No _next/static references found in HTML"
    echo "   This might be a static HTML site, not Next.js"
    WARNINGS=$((WARNINGS + 1))
  fi
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 4: PM2 Process Status (if running locally)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "4️⃣  Checking PM2 process..."

# Only check PM2 if we're checking localhost or if PM2 is available
if [[ "$BASE_URL" == *"localhost"* ]] || [[ "$BASE_URL" == *"127.0.0.1"* ]]; then
  if command -v pm2 >/dev/null 2>&1; then
    # Look for process matching site name
    PM2_STATUS=$(pm2 jlist 2>/dev/null | jq -r ".[] | select(.name | contains(\"cli-$SITE_NAME\") or contains(\"$SITE_NAME\")) | .pm2_env.status" 2>/dev/null || echo "")

    if [ "$PM2_STATUS" = "online" ]; then
      echo "✅ PM2 process running: cli-$SITE_NAME"
    elif [ -n "$PM2_STATUS" ]; then
      echo "❌ PM2 process not online: $PM2_STATUS"
      echo "   Run: pm2 restart cli-$SITE_NAME"
      ISSUES=$((ISSUES + 1))
    else
      echo "⏭️  No PM2 process found for $SITE_NAME"
    fi
  else
    echo "⏭️  PM2 not available on this machine"
  fi
else
  echo "⏭️  Remote deployment, skipping PM2 check"
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Summary
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if [ $ISSUES -eq 0 ] && [ $WARNINGS -eq 0 ]; then
  echo "✅ Deployment verified successfully!"
  echo ""
  echo "$SITE_NAME is live and healthy at $FULL_URL/"
  exit 0
elif [ $ISSUES -eq 0 ]; then
  echo "⚠️  Deployment verified with $WARNINGS warning(s)"
  echo ""
  echo "$SITE_NAME is live but consider reviewing warnings"
  exit 0
else
  echo "❌ Deployment verification failed"
  echo ""
  echo "Found $ISSUES critical issue(s) and $WARNINGS warning(s)"
  echo "Review the checks above and fix issues"
  exit 1
fi
