# Caddyfile for client2server
# Supports multiple server instances via Docker Compose

{
    # Global options
    email your@email.com
    admin off
    auto_https off
}

# ========================================
# WebSocket Load Balancer (port 3843)
# ========================================
ws://:3843 {
    # Backend servers (Docker network DNS)
    to server1:3843 server2:3843
    
    # Load balancing
    lb_try_duration 2s
    lb_try_interval 500ms
    
    # Keep WebSocket connections alive
    websocket
    
    # Health check
    health_check /health {
        interval 10s
        timeout 5s
        fails 2
        passes 1
    }
    
    # Preserve client info
    header_up X-Real-IP {remote}
    header_up X-Forwarded-For {remote}
    header_up X-Forwarded-Proto {scheme}
    header_up X-Client-ID {client_ip}
    
    # Timeouts for long-lived connections
    timeouts {
        read 300s
        write 300s
        idle 300s
    }
}

# ========================================
# HTTP API (port 3844)
# ========================================
:3844 {
    # Health endpoint for each server
    handle /health* {
        respond "OK" 200
    }
    
    # Events webhook (HTTP fallback)
    handle /api/events* {
        reverse_proxy server1:3843
    }
    
    # Router management
    handle /api/routers* {
        reverse_proxy server1:3843
    }
    
    # Command endpoint
    handle /api/command* {
        reverse_proxy server1:3843
    }
    
    # Default
    respond "client2server API" 200
}

# ========================================
# Dashboard (port 80/443)
# ========================================
:80, :443 {
    # Redirect to HTTPS
    respond / https://{$host}/dashboard {302}
}

# Dashboard placeholder (enable if you have a web UI)
# localhost/dashboard {
#     reverse_proxy dashboard:3000
# }

# ========================================
# TLS for HTTPS (optional)
# ========================================
# tls {
#     # Let's Encrypt (automatic)
# }