#!/usr/bin/env bash
# Verify Cloudflare DNS records point to Nginx Proxy only

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
else
    echo "❌ Error: .env file not found"
    exit 1
fi

NGINX_PROXY_IP="${NGINX_PROXY_IP:-20.160.58.99}"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 Verifying Cloudflare DNS Configuration"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Expected Nginx Proxy IP: $NGINX_PROXY_IP"
echo ""

declare -a SERVICES=(
    "explorer.d-bis.org"
    "besu.d-bis.org"
    "blockscout.d-bis.org"
    "monitoring.d-bis.org"
    "wallet.d-bis.org"
    "d-bis.org"
    "www.d-bis.org"
    "rpc.d-bis.org"
    "metrics.d-bis.org"
    "api.d-bis.org"
)

ERRORS=0
for service in "${SERVICES[@]}"; do
    echo -n "Checking $service... "
    
    # Get DNS records from Cloudflare API
    RECORDS=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records?name=$service&type=A" \
        -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
        -H "Content-Type: application/json" 2>/dev/null)
    
    RECORD_COUNT=$(echo "$RECORDS" | python3 -c "import sys, json; data=json.load(sys.stdin); print(len(data.get('result', [])))" 2>/dev/null || echo "0")
    
    if [ "$RECORD_COUNT" = "0" ]; then
        echo "⚠️  No A records found"
        ((ERRORS++))
    elif [ "$RECORD_COUNT" = "1" ]; then
        RECORD_IP=$(echo "$RECORDS" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data['result'][0]['content'])" 2>/dev/null || echo "")
        if [ "$RECORD_IP" = "$NGINX_PROXY_IP" ]; then
            echo "✅ OK ($RECORD_IP)"
        else
            echo "❌ Wrong IP: $RECORD_IP (expected $NGINX_PROXY_IP)"
            ((ERRORS++))
        fi
    else
        echo "⚠️  Multiple records found ($RECORD_COUNT) - duplicates exist"
        ((ERRORS++))
    fi
done

echo ""
if [ $ERRORS -eq 0 ]; then
    echo "✅ All DNS records correctly point to Nginx Proxy"
else
    echo "⚠️  Found $ERRORS issues - run update-dns-to-proxy.sh to fix"
fi
echo ""
