#!/usr/bin/env bash
# Quick test script to verify Cloudflare API credentials

set -euo pipefail

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

# Load .env if exists
if [[ -f "$SCRIPT_DIR/../.env" ]]; then
    source "$SCRIPT_DIR/../.env"
fi

CLOUDFLARE_API_KEY="${CLOUDFLARE_API_KEY:-}"
CLOUDFLARE_EMAIL="${CLOUDFLARE_EMAIL:-}"
CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN:-}"

echo "Testing Cloudflare API credentials..."
echo ""

if [[ -n "$CLOUDFLARE_API_TOKEN" ]]; then
    echo "Testing with API Token..."
    response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/user" \
        -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
        -H "Content-Type: application/json")
    
    success=$(echo "$response" | jq -r '.success // false')
    if [[ "$success" == "true" ]]; then
        email=$(echo "$response" | jq -r '.result.email // "N/A"')
        echo "✓ API Token works! Email: $email"
    else
        error=$(echo "$response" | jq -r '.errors[0].message // "Unknown error"')
        echo "✗ API Token failed: $error"
    fi
elif [[ -n "$CLOUDFLARE_API_KEY" ]]; then
    if [[ -z "$CLOUDFLARE_EMAIL" ]]; then
        echo "✗ CLOUDFLARE_API_KEY requires CLOUDFLARE_EMAIL"
        echo "  Please add CLOUDFLARE_EMAIL to .env file"
    else
        echo "Testing with API Key + Email..."
        response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/user" \
            -H "X-Auth-Email: ${CLOUDFLARE_EMAIL}" \
            -H "X-Auth-Key: ${CLOUDFLARE_API_KEY}" \
            -H "Content-Type: application/json")
        
        success=$(echo "$response" | jq -r '.success // false')
        if [[ "$success" == "true" ]]; then
            email=$(echo "$response" | jq -r '.result.email // "N/A"')
            echo "✓ API Key works! Email: $email"
        else
            error=$(echo "$response" | jq -r '.errors[0].message // "Unknown error"')
            echo "✗ API Key failed: $error"
        fi
    fi
else
    echo "✗ No API credentials found in .env"
fi

