#!/bin/bash
set -e

PROD_DIR="/var/www/sneakerpicks"
STAGING_DIR="/var/www/sneakerpicks-staging"
DEPLOY_FILE="$PROD_DIR/sneakerpicks-deploy.tar.gz"

echo "=== SneakerPicks Deploy ==="

if [ ! -f "$DEPLOY_FILE" ]; then
  echo "❌ Deploy file not found: $DEPLOY_FILE"
  exit 1
fi

# Step 1: Extract to staging
echo "[1/5] Extracting to staging..."
cd "$STAGING_DIR"
tar -xzf "$DEPLOY_FILE"

# Step 2: Install deps
echo "[2/5] Installing dependencies..."
pnpm install --production=false 2>&1 | tail -3

# Step 3: Build staging
echo "[3/5] Building staging..."
if ! pnpm run build 2>&1 | tail -10; then
  echo "❌ STAGING BUILD FAILED - aborting deploy"
  exit 1
fi

# Step 4: Restart staging and test
echo "[4/5] Testing staging..."
pm2 reload sneakerpicks-staging --update-env
sleep 5

STAGING_PORT=3002

# Test key pages
ERRORS=0
for path in "/" "/sneakers" "/deals" "/merken"; do
  STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:$STAGING_PORT$path" --max-time 10)
  if [ "$STATUS" != "200" ]; then
    echo "❌ STAGING TEST FAILED: $path returned $STATUS"
    ERRORS=$((ERRORS + 1))
  else
    echo "✅ $path → $STATUS"
  fi
done

if [ $ERRORS -gt 0 ]; then
  echo "❌ $ERRORS pages failed - NOT deploying to production"
  exit 1
fi

echo "✅ All staging tests passed!"

# Step 5: Deploy to production
echo "[5/5] Deploying to production (zero-downtime)..."
cd "$PROD_DIR"
tar -xzf "$DEPLOY_FILE"
pnpm install --production=false 2>&1 | tail -3

if ! pnpm run build 2>&1 | tail -10; then
  echo "❌ PRODUCTION BUILD FAILED"
  exit 1
fi

pm2 reload sneakerpicks
sleep 3

# Regenerate sitemaps (build wipes dist/client/)
echo "Regenerating sitemaps..."
python3 scripts/generate-sitemaps.py 2>&1 | tail -3

# Regenerate llms.txt (build wipes dist/client/)
echo "Regenerating llms.txt..."
python3 scripts/generate-llms-txt.py 2>&1 | tail -3

# Final verification
PROD_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:3001/" --max-time 10)
if [ "$PROD_STATUS" = "200" ]; then
  echo "✅ Production is live and healthy"
else
  echo "⚠️ Production returned $PROD_STATUS - check logs"
fi

# Cleanup
rm -f "$DEPLOY_FILE"
echo "=== Deploy complete ==="
