#!/bin/bash
# validate-deployment.sh
# Validates a CLI site works in both deployment modes (SSR + static export)
#
# Usage: ./validate-deployment.sh <site-directory>
#
# Validates:
# 1. next.config.ts structure (basePath/trailingSlash at root)
# 2. Static export build
# 3. SSR build
# 4. ecosystem.config.js (if using PM2)
# 5. Port availability (if assigned)

set -e

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

SITE_DIR=$1
SITE_NAME=$(basename "$SITE_DIR")

if [ -z "$SITE_DIR" ]; then
  echo "Usage: $0 <site-directory>"
  echo ""
  echo "Examples:"
  echo "  $0 cli-made/silicon-bali"
  echo "  $0 ../my-site"
  exit 1
fi

if [ ! -d "$SITE_DIR" ]; then
  echo "❌ Directory not found: $SITE_DIR"
  exit 1
fi

echo "🔍 Validating $SITE_NAME for deployment..."
echo ""

ISSUES=0
WARNINGS=0

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 1: next.config.ts Structure
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "1️⃣  Checking next.config.ts structure..."

if [ ! -f "$SITE_DIR/next.config.ts" ] && [ ! -f "$SITE_DIR/next.config.js" ] && [ ! -f "$SITE_DIR/next.config.mjs" ]; then
  echo "❌ No next.config.ts/js/mjs found"
  ISSUES=$((ISSUES + 1))
else
  # Find the config file
  CONFIG_FILE=""
  if [ -f "$SITE_DIR/next.config.ts" ]; then
    CONFIG_FILE="$SITE_DIR/next.config.ts"
  elif [ -f "$SITE_DIR/next.config.js" ]; then
    CONFIG_FILE="$SITE_DIR/next.config.js"
  elif [ -f "$SITE_DIR/next.config.mjs" ]; then
    CONFIG_FILE="$SITE_DIR/next.config.mjs"
  fi

  # Extract first 20 lines of config (before conditional blocks)
  HEAD_LINES=$(head -20 "$CONFIG_FILE")

  # Check for basePath at root level
  if ! echo "$HEAD_LINES" | grep -q "basePath:"; then
    echo "❌ basePath must be at root level (not conditional)"
    echo "   Current: basePath found after line 20 or not at all"
    echo "   Fix: Move 'basePath: \"/cli/$SITE_NAME\"' to top of nextConfig object"
    ISSUES=$((ISSUES + 1))
  else
    echo "✅ basePath at root level"
  fi

  # Check for trailingSlash at root level
  if ! echo "$HEAD_LINES" | grep -q "trailingSlash:"; then
    echo "❌ trailingSlash must be at root level (not conditional)"
    echo "   Current: trailingSlash found after line 20 or not at all"
    echo "   Fix: Move 'trailingSlash: true' to top of nextConfig object"
    ISSUES=$((ISSUES + 1))
  else
    echo "✅ trailingSlash at root level"
  fi

  # Check that output:'export' is NOT at root (should be conditional)
  if echo "$HEAD_LINES" | grep -q "output.*:.*['\"]export['\"]"; then
    echo "⚠️  output:'export' should be conditional (inside isExport check)"
    echo "   Current: output:'export' is always present"
    echo "   This will break SSR deployments"
    WARNINGS=$((WARNINGS + 1))
  else
    echo "✅ output:'export' is conditional (or not present)"
  fi
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 2: Static Export Build
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "2️⃣  Testing static export build..."

cd "$SITE_DIR"

# Clean previous builds
rm -rf out .next 2>/dev/null || true

if [ ! -f "package.json" ]; then
  echo "⏭️  No package.json, skipping build tests"
else
  # Try static export
  echo "   Building with STATIC_EXPORT=true..."
  if STATIC_EXPORT=true npm run build >/dev/null 2>&1; then
    if [ -d "out" ]; then
      OUT_SIZE=$(du -sh out | cut -f1)
      echo "✅ Static export successful (size: $OUT_SIZE)"
    else
      echo "❌ Static export failed (no out/ directory created)"
      ISSUES=$((ISSUES + 1))
    fi
  else
    echo "❌ Static export build failed"
    echo "   Run: cd $SITE_DIR && STATIC_EXPORT=true npm run build"
    ISSUES=$((ISSUES + 1))
  fi
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 3: SSR Build
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "3️⃣  Testing SSR build..."

# Clean previous builds
rm -rf out .next 2>/dev/null || true

if [ ! -f "package.json" ]; then
  echo "⏭️  No package.json, skipping SSR build"
else
  echo "   Building SSR mode..."
  if npm run build >/dev/null 2>&1; then
    if [ -d ".next" ]; then
      NEXT_SIZE=$(du -sh .next | cut -f1)
      echo "✅ SSR build successful (size: $NEXT_SIZE)"
    else
      echo "❌ SSR build failed (no .next/ directory)"
      ISSUES=$((ISSUES + 1))
    fi
  else
    echo "❌ SSR build failed"
    echo "   Run: cd $SITE_DIR && npm run build"
    ISSUES=$((ISSUES + 1))
  fi
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 4: ecosystem.config.js (if using PM2)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

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

if [ -f "ecosystem.config.js" ] || [ -f "ecosystem.config.cjs" ]; then
  ECOSYSTEM_FILE=$([ -f "ecosystem.config.js" ] && echo "ecosystem.config.js" || echo "ecosystem.config.cjs")

  # Check for port assignment
  if ! grep -q "PORT" "$ECOSYSTEM_FILE"; then
    echo "⚠️  No PORT environment variable in $ECOSYSTEM_FILE"
    echo "   Add: env: { PORT: 'XXXX' }"
    WARNINGS=$((WARNINGS + 1))
  else
    echo "✅ PORT configured in $ECOSYSTEM_FILE"
  fi

  # Check for basePath in name
  if ! grep -q "name.*cli.*$SITE_NAME" "$ECOSYSTEM_FILE"; then
    echo "⚠️  App name should match directory: cli-$SITE_NAME"
    WARNINGS=$((WARNINGS + 1))
  else
    echo "✅ App name matches directory"
  fi
else
  echo "⏭️  No ecosystem.config.js (not using PM2)"
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Check 5: Port Availability (if assigned)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo "5️⃣  Checking port assignment..."

PORTS_FILE="../${WS_DIR_CLI}/ports.json"
if [ -f "$PORTS_FILE" ]; then
  ASSIGNED_PORT=$(jq -r ".\"$SITE_NAME\" // empty" "$PORTS_FILE" 2>/dev/null || echo "")

  if [ -n "$ASSIGNED_PORT" ] && [ "$ASSIGNED_PORT" != "null" ]; then
    echo "✅ Port assigned: $ASSIGNED_PORT"

    # Check if port is in use (only on current machine)
    if command -v lsof >/dev/null 2>&1; then
      if lsof -i ":$ASSIGNED_PORT" >/dev/null 2>&1; then
        echo "⚠️  Port $ASSIGNED_PORT is currently in use"
        lsof -i ":$ASSIGNED_PORT" | head -2
        WARNINGS=$((WARNINGS + 1))
      else
        echo "✅ Port $ASSIGNED_PORT is available"
      fi
    fi
  else
    echo "⚠️  No port assigned in ports.json"
    echo "   Run: ./scripts/assign-port.sh $SITE_NAME"
    WARNINGS=$((WARNINGS + 1))
  fi
else
  echo "⏭️  No ports.json file"
fi

echo ""

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

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

if [ $ISSUES -eq 0 ] && [ $WARNINGS -eq 0 ]; then
  echo "✅ All validation checks passed!"
  echo ""
  echo "$SITE_NAME is ready for deployment"
  exit 0
elif [ $ISSUES -eq 0 ]; then
  echo "⚠️  Validation passed with $WARNINGS warning(s)"
  echo ""
  echo "$SITE_NAME can be deployed, but consider fixing warnings"
  exit 0
else
  echo "❌ Validation failed with $ISSUES blocking issue(s) and $WARNINGS warning(s)"
  echo ""
  echo "Fix the issues above before deploying to production"
  exit 1
fi
