#!/bin/bash
# Create missing DNS records for all services
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}"

if [ -z "$CLOUDFLARE_ZONE_ID" ]; then
    log_error "CLOUDFLARE_ZONE_ID not set"
    exit 1
fi

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

log_info "Creating DNS records..."
log_info "Tunnel Target: $TUNNEL_TARGET"

create_dns_record() {
    local zone_id="$1"
    local domain_name="$2"
    local target="$3"
    
    local data=$(jq -n --arg name "$domain_name" --arg target "$target" '{
        type: "CNAME",
        name: $name,
        content: $target,
        proxied: true,
        ttl: 1
    }')
    
    local response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records?name=$domain_name" "${AUTH_HEADERS[@]}" -H "Content-Type: application/json")
    local record_id=$(echo "$response" | jq -r '.result[0].id // empty' 2>/dev/null || echo "")
    
    if [ -n "$record_id" ] && [ "$record_id" != "null" ]; then
        log_info "Updating existing record: $domain_name"
        response=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$record_id" "${AUTH_HEADERS[@]}" -H "Content-Type: application/json" --data "$data")
    else
        log_info "Creating new record: $domain_name"
        response=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records" "${AUTH_HEADERS[@]}" -H "Content-Type: application/json" --data "$data")
    fi
    
    if echo "$response" | jq -e '.success' >/dev/null 2>&1; then
        log_success "DNS record configured: $domain_name"
        return 0
    else
        log_error "Failed to configure DNS: $domain_name"
        return 1
    fi
}

DOMAINS_DBIS=(
    "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"
)

DOMAINS_MIM4U=(
    "mim4u.org"
    "www.mim4u.org"
)

SUCCESS=0
FAILED=0

for domain in "${DOMAINS_DBIS[@]}"; do
    if create_dns_record "$CLOUDFLARE_ZONE_ID" "$domain" "$TUNNEL_TARGET"; then
        SUCCESS=$((SUCCESS + 1))
    else
        FAILED=$((FAILED + 1))
    fi
done

if [ -n "$CLOUDFLARE_ZONE_ID_MIM4U" ]; then
    for domain in "${DOMAINS_MIM4U[@]}"; do
        if create_dns_record "$CLOUDFLARE_ZONE_ID_MIM4U" "$domain" "$TUNNEL_TARGET"; then
            SUCCESS=$((SUCCESS + 1))
        else
            FAILED=$((FAILED + 1))
        fi
    done
fi

echo ""
echo "Summary: $SUCCESS succeeded, $FAILED failed"
exit $FAILED
