#!/usr/bin/env bash
# Add Cloudflare credentials to .env file
# Usage: ./scripts/deployment/add-cloudflare-env.sh <zone-id> <api-token>

set -euo pipefail


SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
ENV_FILE="${PROJECT_ROOT}/.env"

log() {
    log_success "[INFO] $1"
}

error() {
    log_error "[ERROR] $1"
    exit 1
}

warn() {
    log_warn "[WARNING] $1"
}

info() {
    log_info "[INFO] $1"
}

prompt() {
    log_info "[PROMPT] $1"
}

# Get Zone ID
if [ $# -ge 1 ] && [ -n "$1" ]; then
    ZONE_ID="$1"
else
    prompt "Enter Cloudflare Zone ID:"
    read -r ZONE_ID
    if [ -z "$ZONE_ID" ]; then
        error "Zone ID is required"
    fi
fi

# Get API Token
if [ $# -ge 2 ] && [ -n "$2" ]; then
    API_TOKEN="$2"
else
    prompt "Enter Cloudflare API Token:"
    read -rs API_TOKEN
    echo
    if [ -z "$API_TOKEN" ]; then
        error "API Token is required"
    fi
fi

# Validate Zone ID format (should be 32 character hex string)
if ! [[ "$ZONE_ID" =~ ^[a-f0-9]{32}$ ]]; then
    warn "Zone ID format may be incorrect (expected 32 character hex string)"
fi

# Create .env file if it doesn't exist
if [ ! -f "$ENV_FILE" ]; then
    log "Creating .env file..."
    touch "$ENV_FILE"
fi

# Update or add CLOUDFLARE_ZONE_ID
if grep -q "^CLOUDFLARE_ZONE_ID=" "$ENV_FILE" 2>/dev/null; then
    if [[ "$OSTYPE" == "darwin"* ]]; then
        sed -i '' "s|^CLOUDFLARE_ZONE_ID=.*|CLOUDFLARE_ZONE_ID=$ZONE_ID|" "$ENV_FILE"
    else
        sed -i "s|^CLOUDFLARE_ZONE_ID=.*|CLOUDFLARE_ZONE_ID=$ZONE_ID|" "$ENV_FILE"
    fi
    log "Updated CLOUDFLARE_ZONE_ID"
else
    echo "CLOUDFLARE_ZONE_ID=$ZONE_ID" >> "$ENV_FILE"
    log "Added CLOUDFLARE_ZONE_ID"
fi

# Update or add CLOUDFLARE_API_TOKEN
if grep -q "^CLOUDFLARE_API_TOKEN=" "$ENV_FILE" 2>/dev/null; then
    if [[ "$OSTYPE" == "darwin"* ]]; then
        sed -i '' "s|^CLOUDFLARE_API_TOKEN=.*|CLOUDFLARE_API_TOKEN=$API_TOKEN|" "$ENV_FILE"
    else
        sed -i "s|^CLOUDFLARE_API_TOKEN=.*|CLOUDFLARE_API_TOKEN=$API_TOKEN|" "$ENV_FILE"
    fi
    log "Updated CLOUDFLARE_API_TOKEN"
else
    echo "CLOUDFLARE_API_TOKEN=$API_TOKEN" >> "$ENV_FILE"
    log "Added CLOUDFLARE_API_TOKEN"
fi

log "Cloudflare credentials added to .env file"
log "Zone ID: $ZONE_ID"
log "API Token: *** (hidden)"

# Test the token (optional)
info "Testing Cloudflare API token..."
TEST_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID" \
    -H "Authorization: Bearer $API_TOKEN" \
    -H "Content-Type: application/json" 2>/dev/null || echo "")

if echo "$TEST_RESPONSE" | grep -q '"success":true' 2>/dev/null; then
    ZONE_NAME=$(echo "$TEST_RESPONSE" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 || echo "unknown")
    log "✅ API token is valid! Zone: $ZONE_NAME"
else
    warn "⚠️  Could not verify API token. Please check:"
    warn "   1. Zone ID is correct"
    warn "   2. API token has correct permissions"
    warn "   3. API token hasn't expired"
fi

