#!/bin/bash
# Verify DNS records and test service accessibility
set -euo pipefail

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

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

cd "$PROJECT_ROOT"

if [ ! -f .env ]; then
    log_error ".env file not found"
    exit 1
fi

set +u
source .env 2>/dev/null || true
set -u

CLOUDFLARE_ZONE_ID="${CLOUDFLARE_ZONE_ID:-}"
CLOUDFLARE_ZONE_ID_MIM4U="${CLOUDFLARE_ZONE_ID_MIM4U_ORG:-}"
CLOUDFLARE_EMAIL="${CLOUDFLARE_EMAIL:-}"
CLOUDFLARE_API_KEY="${CLOUDFLARE_API_KEY:-}"
CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN:-}"
CLOUDFLARE_TUNNEL_ID="${CLOUDFLARE_TUNNEL_ID:-10ab22da-8ea3-4e2e-a896-27ece2211a05}"

TUNNEL_TARGET="${CLOUDFLARE_TUNNEL_ID}.cfargotunnel.com"

if [ -n "$CLOUDFLARE_API_TOKEN" ]; then
    AUTH_HEADERS=(-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN")
else
    AUTH_HEADERS=(-H "X-Auth-Email: $CLOUDFLARE_EMAIL" -H "X-Auth-Key: $CLOUDFLARE_API_KEY")
fi

echo ""
echo -e "${CYAN}=== DNS Records Verification ===${NC}"
echo ""

DOMAINS=(
    "rpc-http-pub.d-bis.org"
    "rpc-ws-pub.d-bis.org"
    "rpc-http-prv.d-bis.org"
    "rpc-ws-prv.d-bis.org"
    "dbis-admin.d-bis.org"
    "dbis-api.d-bis.org"
    "dbis-api-2.d-bis.org"
    "mim4u.org"
    "www.mim4u.org"
)

VALID=0
INVALID=0

for domain in "${DOMAINS[@]}"; do
    if [[ "$domain" == *.mim4u.org ]]; then
        ZONE_ID="$CLOUDFLARE_ZONE_ID_MIM4U"
    else
        ZONE_ID="$CLOUDFLARE_ZONE_ID"
    fi
    
    if [ -z "$ZONE_ID" ]; then
        log_warn "Skipping $domain (zone ID not configured)"
        continue
    fi
    
    response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$domain" "${AUTH_HEADERS[@]}" -H "Content-Type: application/json")
    record_type=$(echo "$response" | jq -r '.result[0].type // empty' 2>/dev/null || echo "")
    record_content=$(echo "$response" | jq -r '.result[0].content // empty' 2>/dev/null || echo "")
    record_proxied=$(echo "$response" | jq -r '.result[0].proxied // false' 2>/dev/null || echo "false")
    dns_result=$(dig +short "$domain" @8.8.8.8 2>/dev/null | head -1 || echo "")
    
    if [ "$record_type" = "CNAME" ] && [ "$record_content" = "$TUNNEL_TARGET" ] && [ "$record_proxied" = "true" ]; then
        log_success "$domain: ✓ CNAME → $TUNNEL_TARGET (proxied)"
        if [ -n "$dns_result" ]; then
            echo "         DNS resolves to: $dns_result"
        fi
        VALID=$((VALID + 1))
    else
        log_error "$domain: ❌ Type=$record_type, Target=$record_content, Proxied=$record_proxied"
        INVALID=$((INVALID + 1))
    fi
done

echo ""
echo -e "${CYAN}=== Service Accessibility Test ===${NC}"
echo ""

HTTP_DOMAINS=(
    "rpc-http-pub.d-bis.org"
    "dbis-admin.d-bis.org"
    "dbis-api.d-bis.org"
    "mim4u.org"
)

ACCESSIBLE=0
NOT_ACCESSIBLE=0

for domain in "${HTTP_DOMAINS[@]}"; do
    http_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://${domain}" 2>/dev/null || echo "000")
    if [[ "$http_code" =~ ^(200|301|302|403)$ ]]; then
        log_success "$domain: ✓ Accessible (HTTP $http_code)"
        ACCESSIBLE=$((ACCESSIBLE + 1))
    else
        log_warn "$domain: ⚠️  Not accessible (HTTP $http_code)"
        NOT_ACCESSIBLE=$((NOT_ACCESSIBLE + 1))
    fi
done

echo ""
echo -e "${CYAN}=== Summary ===${NC}"
echo "DNS Records: $VALID valid, $INVALID invalid"
echo "Service Access: $ACCESSIBLE accessible, $NOT_ACCESSIBLE not accessible"
echo ""

if [ $INVALID -eq 0 ] && [ $NOT_ACCESSIBLE -eq 0 ]; then
    log_success "All DNS records and services are working!"
    exit 0
elif [ $INVALID -eq 0 ]; then
    log_warn "DNS records OK, but some services are not accessible"
    exit 1
else
    log_error "Some DNS records need attention"
    exit 1
fi
