#!/usr/bin/env bash
# Check Cloudflare DNS entries for sankofa.nexus domain
set -euo pipefail

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"; }

# Load .env
if [ -f "$SCRIPT_DIR/../.env" ]; then
    source "$SCRIPT_DIR/../.env" 2>/dev/null
elif [ -f ~/.env ]; then
    source ~/.env 2>/dev/null
fi

# Get API credentials
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
    AUTH_METHOD="token"
    log_info "Using API token authentication"
elif [ -n "${CLOUDFLARE_API_KEY:-}" ] && [ -n "${CLOUDFLARE_EMAIL:-}" ]; then
    AUTH_METHOD="key"
    log_info "Using API key + email authentication"
else
    log_error "Cloudflare credentials not found!"
    log_info "Please set in .env: CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL"
    exit 1
fi

DOMAIN="sankofa.nexus"
log_info "=== Checking Cloudflare DNS for ${DOMAIN} ==="
echo ""

# Find zone ID
log_info "Finding zone ID for ${DOMAIN}..."
if [ "$AUTH_METHOD" = "token" ]; then
    ZONES_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}" \
        -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
        -H "Content-Type: application/json")
else
    ZONES_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}" \
        -H "X-Auth-Email: ${CLOUDFLARE_EMAIL}" \
        -H "X-Auth-Key: ${CLOUDFLARE_API_KEY}" \
        -H "Content-Type: application/json")
fi

if ! echo "$ZONES_RESPONSE" | jq -e '.success' >/dev/null 2>&1; then
    log_error "Failed to query Cloudflare API"
    echo "$ZONES_RESPONSE" | jq '.' 2>/dev/null || echo "$ZONES_RESPONSE"
    exit 1
fi

ZONE_COUNT=$(echo "$ZONES_RESPONSE" | jq '.result | length')

if [ "$ZONE_COUNT" -eq 0 ]; then
    log_warn "Domain ${DOMAIN} is NOT in Cloudflare"
    log_info "This is expected - sankofa.nexus should be internal DNS only"
    exit 0
fi

ZONE_ID=$(echo "$ZONES_RESPONSE" | jq -r '.result[0].id')
ZONE_NAME=$(echo "$ZONES_RESPONSE" | jq -r '.result[0].name')
log_success "Found zone: ${ZONE_NAME} (ID: ${ZONE_ID})"
echo ""

# Get DNS records
log_info "Retrieving DNS records..."
if [ "$AUTH_METHOD" = "token" ]; then
    DNS_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
        -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
        -H "Content-Type: application/json")
else
    DNS_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
        -H "X-Auth-Email: ${CLOUDFLARE_EMAIL}" \
        -H "X-Auth-Key: ${CLOUDFLARE_API_KEY}" \
        -H "Content-Type: application/json")
fi

RECORD_COUNT=$(echo "$DNS_RESPONSE" | jq '.result | length')
echo ""
log_info "=== DNS Records for ${DOMAIN} ==="
echo ""

if [ "$RECORD_COUNT" -eq 0 ]; then
    log_warn "No DNS records found"
else
    echo "$DNS_RESPONSE" | jq -r '.result[] | "\(.type) | \(.name) | \(.content) | Proxied: \(.proxied // false)"' | column -t -s '|' || echo "$DNS_RESPONSE" | jq '.result[]'
    echo ""
    log_info "Total: ${RECORD_COUNT} records"
    echo ""
    log_info "Full JSON:"
    echo "$DNS_RESPONSE" | jq '.result[]'
fi
