#!/bin/bash
# Create NPMplus proxy host for cross-all.defi-oracle.io via API
# Based on update-npmplus-proxy-hosts-api.sh pattern

set -euo pipefail

# Credentials (from NPMPLUS_MIGRATION_COMPLETE_STATUS.md)
NPM_URL="${NPM_URL:-https://192.168.11.166:81}"
NPM_EMAIL="${NPM_EMAIL:-admin@example.org}"
NPM_PASSWORD="${NPM_PASSWORD:-ce8219e321e1cd97bd590fb792d3caeb7e2e3b94ca7e20124acaf253f911ff72}"

DOMAIN="cross-all.defi-oracle.io"
TARGET_IP="192.168.11.211"
TARGET_PORT="80"

# 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"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CREATING NPMPLUS PROXY HOST: $DOMAIN"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Step 1: Authenticate
log_info "Step 1: Authenticating to NPMplus..."
TOKEN_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/tokens" \
    -H "Content-Type: application/json" \
    -d "{\"identity\":\"$NPM_EMAIL\",\"secret\":\"$NPM_PASSWORD\"}" 2>/dev/null || echo "{}")

TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.token // empty' 2>/dev/null || echo "")

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
    ERROR_MSG=$(echo "$TOKEN_RESPONSE" | jq -r '.error.message // "Unknown error"' 2>/dev/null || echo "$TOKEN_RESPONSE")
    log_error "Authentication failed: $ERROR_MSG"
    log_info "Response: $TOKEN_RESPONSE"
    exit 1
fi

log_success "Authentication successful"
echo ""

# Step 2: Check if proxy host already exists
log_info "Step 2: Checking for existing proxy host..."
EXISTING_HOSTS=$(curl -s -k -X GET "$NPM_URL/api/nginx/proxy-hosts" \
    -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo "[]")

EXISTING_ID=$(echo "$EXISTING_HOSTS" | jq -r ".[] | select(.domain_names[]? == \"$DOMAIN\") | .id" 2>/dev/null | head -1)

if [ -n "$EXISTING_ID" ] && [ "$EXISTING_ID" != "null" ]; then
    log_warn "Proxy host for $DOMAIN already exists (ID: $EXISTING_ID)"
    read -p "Update existing proxy host? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipping. Existing proxy host: $EXISTING_ID"
        exit 0
    fi
    UPDATE_MODE=true
else
    UPDATE_MODE=false
fi

# Step 3: Create/Update proxy host
log_info "Step 3: ${UPDATE_MODE:-false} && echo "Updating" || echo "Creating"} proxy host..."

# Build payload - NPMplus requires specific field names
PAYLOAD=$(jq -n \
    --arg domain "$DOMAIN" \
    --arg host "$TARGET_IP" \
    --arg port "$TARGET_PORT" \
    '{
        "domain_names": [$domain],
        "forward_scheme": "http",
        "forward_host": $host,
        "forward_port": ($port | tonumber),
        "cache_assets": true,
        "block_exploits": true,
        "websockets_support": true,
        "access_list_id": "0",
        "advanced_config": "",
        "locations": []
    }')

if [ "$UPDATE_MODE" = true ]; then
    RESPONSE=$(curl -s -k -X PUT "$NPM_URL/api/nginx/proxy-hosts/$EXISTING_ID" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$PAYLOAD" 2>/dev/null || echo "{}")
    
    ACTION="updated"
else
    RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/proxy-hosts" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$PAYLOAD" 2>/dev/null || echo "{}")
    
    ACTION="created"
fi

PROXY_ID=$(echo "$RESPONSE" | jq -r '.id // empty' 2>/dev/null || echo "")
ERROR_MSG=$(echo "$RESPONSE" | jq -r '.error.message // empty' 2>/dev/null || echo "")

if [ -n "$ERROR_MSG" ] && [ "$ERROR_MSG" != "null" ]; then
    log_error "Failed to $ACTION proxy host: $ERROR_MSG"
    log_info "Response: $RESPONSE"
    exit 1
fi

if [ -z "$PROXY_ID" ] || [ "$PROXY_ID" = "null" ]; then
    log_error "Failed to $ACTION proxy host: Invalid response"
    log_info "Response: $RESPONSE"
    exit 1
fi

log_success "Proxy host $ACTION successfully (ID: $PROXY_ID)"
echo ""

# Step 4: Request SSL certificate
log_info "Step 4: Requesting SSL certificate..."

SSL_PAYLOAD=$(jq -n '{
    "force_ssl": true,
    "http2_support": true,
    "hsts_enabled": true,
    "hsts_subdomains": false,
    "certificate_id": 0
}')

SSL_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/proxy-hosts/$PROXY_ID/ssl" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$SSL_PAYLOAD" 2>/dev/null || echo "{}")

SSL_ERROR=$(echo "$SSL_RESPONSE" | jq -r '.error.message // empty' 2>/dev/null || echo "")
SSL_SUCCESS=$(echo "$SSL_RESPONSE" | jq -r '.success // empty' 2>/dev/null || echo "")

if [ -n "$SSL_ERROR" ] && [ "$SSL_ERROR" != "null" ]; then
    log_warn "SSL configuration issue: $SSL_ERROR"
    log_info "You may need to request SSL certificate manually via web interface"
else
    log_success "SSL configuration updated"
    log_info "Certificate issuance may take 1-2 minutes"
fi

echo ""

# Step 5: Reload NPMplus
log_info "Step 5: Reloading NPMplus..."
RELOAD_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/reload" \
    -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo "{}")

log_success "NPMplus configuration reloaded"
echo ""

# Step 6: Verify
log_info "Step 6: Verifying configuration..."
sleep 3

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "http://$DOMAIN/" 2>/dev/null || echo "000")
HTTPS_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 -k "https://$DOMAIN/" 2>/dev/null || echo "000")

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CONFIGURATION COMPLETE"
log_info "═══════════════════════════════════════════════════════════"
echo ""

if [ "$HTTPS_CODE" = "200" ]; then
    log_success "✅ Domain is accessible via HTTPS!"
    echo ""
    log_success "🌐 Access your deployment:"
    log_success "   https://$DOMAIN/"
    log_success "   https://$DOMAIN/admin"
elif [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "301" ] || [ "$HTTP_CODE" = "302" ]; then
    log_warn "⚠️  Domain accessible via HTTP (SSL certificate pending)"
    echo ""
    log_info "🌐 Access your deployment:"
    log_info "   http://$DOMAIN/ (HTTP)"
    log_info "   https://$DOMAIN/ (SSL certificate pending - check NPMplus)"
else
    log_warn "⚠️  Domain not yet accessible (HTTP: $HTTP_CODE, HTTPS: $HTTPS_CODE)"
    echo ""
    log_info "Possible reasons:"
    log_info "  1. DNS not configured or not propagated"
    log_info "  2. SSL certificate still being issued (wait 1-2 minutes)"
    log_info "  3. Network routing issue"
    echo ""
    log_info "Verify DNS: dig $DOMAIN"
    log_info "Check NPMplus: $NPM_URL"
fi

echo ""
log_success "Proxy host ID: $PROXY_ID"
log_info "Direct access: http://$TARGET_IP/"

echo ""
