# mTLS policy for node-facing routes (SEC-01)
(mtls_policy) {
    client_auth {
        mode require_and_verify
        trusted_ca_cert_file /etc/certs/internal-ca.crt
    }
    # Forward client certificate CN to application for defense-in-depth validation
    header X-SSL-Client-CN {tls_client_subject}
}

# HTTPS — full dashboard (trusted after CA is installed)
:443 {
    tls /etc/certs/caddy.crt /etc/certs/caddy.key

    # Node-facing routes with mTLS enforcement
    @mtls_clients {
        path /work/pull /heartbeat
    }

    handle @mtls_clients {
        import mtls_policy
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # API Proxy
    handle /api/* {
        uri strip_prefix /api
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # Pass-through routes served directly by agent (no /api prefix)
    handle /auth/* {
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }
    handle /ws {
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # Docs
    handle /docs/* {
        reverse_proxy docs:80
    }

    # Dashboard fallback
    handle {
        reverse_proxy dashboard:80
    }
}

# HTTP — bootstrap access
# /system/root-ca and /system/root-ca-installer are served over plain HTTP
# so new devices can install the CA before they trust HTTPS.
# All other routes are also served here (useful during initial setup).
:80 {
    # CA bootstrap endpoints — proxied to agent, no TLS required by caller
    handle /system/root-ca* {
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # API Proxy
    handle /api/* {
        uri strip_prefix /api
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # Auth + WS
    handle /auth/* {
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }
    handle /ws {
        reverse_proxy https://agent:8001 {
            transport http {
                tls_trusted_ca_certs /etc/certs/internal-ca.crt
            }
        }
    }

    # Docs
    handle /docs/* {
        reverse_proxy docs:80
    }

    # Dashboard fallback
    handle {
        reverse_proxy dashboard:80
    }
}
