import type { Handle } from '@sveltejs/kit';

// Reverse-proxy `/api/*` requests through to the backend container.
//
// Mangalord's compose runs SvelteKit (this process) on :3000 and axum on
// :8080. The browser only ever talks to :3000, so cookies stay
// same-origin and `CORS_ALLOWED_ORIGINS` can stay empty in the default
// deploy. The backend hostname comes from `BACKEND_URL` (compose wires
// `http://backend:8080`); for `npm run dev` we fall back to the same
// localhost target the vite proxy uses, which keeps the dev story
// consistent even if someone bypasses the vite proxy.

const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:8080';

/**
 * Hop-by-hop headers per RFC 7230 §6.1. These are scoped to a single
 * transport-level connection and must not be forwarded by a proxy.
 * Plus `host` and `content-length`: `host` would mislead the backend
 * about its origin, and `content-length` is recomputed by the upstream
 * fetch from the body stream.
 */
const HOP_BY_HOP_HEADERS = [
    'host',
    'content-length',
    'connection',
    'keep-alive',
    'proxy-authenticate',
    'proxy-authorization',
    'te',
    'trailer',
    'transfer-encoding',
    'upgrade'
];

/**
 * Return a copy of `src` with the hop-by-hop headers removed. Applied to
 * BOTH the proxied request and the proxied response: per RFC 7230 §6.1 a
 * proxy must not forward connection-scoped headers in either direction.
 * On the response side this also drops the upstream `content-length` /
 * `transfer-encoding`, which the runtime recomputes for the re-streamed
 * body — forwarding the upstream values risks a framing mismatch.
 * Exported for unit-test coverage.
 */
export function stripHopByHopHeaders(src: Headers): Headers {
    const out = new Headers(src);
    for (const h of HOP_BY_HOP_HEADERS) out.delete(h);
    return out;
}

/**
 * Stamp the real client address onto `x-forwarded-for` for the upstream
 * request so axum can key its per-IP auth rate limiter on the actual client
 * (the backend only honours this when `AUTH_TRUSTED_PROXY=true`). We
 * **override** rather than append, and drop any incoming `x-forwarded-for` /
 * `x-real-ip`, so a browser can't spoof its own IP to dodge the limit — this
 * proxy is the single trusted hop. A missing/blank address leaves the headers
 * untouched (backend then falls back to its shared bucket). Exported for
 * unit-test coverage.
 */
export function setForwardedFor(headers: Headers, clientAddress: string | undefined): Headers {
    headers.delete('x-real-ip');
    if (clientAddress && clientAddress.trim() !== '') {
        headers.set('x-forwarded-for', clientAddress.trim());
    } else {
        headers.delete('x-forwarded-for');
    }
    return headers;
}

/**
 * Cap each proxied request at 5 minutes. The bound exists to surface
 * a wedged backend (stuck on a slow DB query, deadlocked, etc.) as a
 * 502 rather than letting the browser request hang indefinitely.
 *
 * The default leans toward the slow-upload end of the spectrum: at a
 * 1 Mbps upstream, a 200 MiB chapter upload (the default
 * `MAX_REQUEST_BYTES` cap) needs ~27 minutes; 300 s covers the more
 * realistic 25 Mbps urban-broadband case (~64 s for the same upload)
 * with comfortable headroom. Operators serving very slow clients
 * should raise `BACKEND_PROXY_TIMEOUT_MS`; operators behind a
 * tighter upstream proxy may want to lower it. A future improvement
 * is an idle-based timeout (reset per chunk) instead of this
 * wall-clock budget — that's a fair bit more code, deferred.
 *
 * SSE streams (`Accept: text/event-stream`) are exempt — see
 * `shouldBypassProxyTimeout`. A wall-clock abort on a long-lived
 * stream would tear the connection down every 5 min and force the
 * browser to reconnect, which flickers the admin dashboard.
 */
const PROXY_TIMEOUT_MS = (() => {
    const raw = process.env.BACKEND_PROXY_TIMEOUT_MS;
    const n = raw ? Number(raw) : 300_000;
    return Number.isFinite(n) && n > 0 ? n : 300_000;
})();

/**
 * Whether the proxy should skip its wall-clock timeout for this
 * request. SSE clients open a single connection and stay subscribed
 * for the lifetime of the page; aborting on a wall-clock budget would
 * tear down the live admin dashboard every 5 min. Exported for unit
 * test coverage.
 */
export function shouldBypassProxyTimeout(headers: Headers): boolean {
    const accept = headers.get('accept') ?? '';
    return accept.toLowerCase().includes('text/event-stream');
}

export const handle: Handle = async ({ event, resolve }) => {
    if (event.url.pathname.startsWith('/api/')) {
        const target = `${BACKEND_URL}${event.url.pathname}${event.url.search}`;

        const headers = stripHopByHopHeaders(event.request.headers);
        // Forward the real client IP for the backend's per-IP auth rate
        // limiter, overriding any client-supplied value (anti-spoof).
        // `getClientAddress()` throws if the adapter can't determine it — fall
        // back to stripping the header so no spoofed value survives.
        let clientAddress: string | undefined;
        try {
            clientAddress = event.getClientAddress();
        } catch {
            clientAddress = undefined;
        }
        setForwardedFor(headers, clientAddress);

        // AbortController times the upstream fetch out so a backend
        // wedged on a slow DB query doesn't keep the browser request
        // hanging forever. The `signal` is also wired into the
        // RequestInit so the body stream is cancelled cleanly. For
        // SSE streams the timer is suppressed so a long-lived stream
        // isn't torn down on the 5-minute mark — see T1 in the audit.
        const bypassTimeout = shouldBypassProxyTimeout(event.request.headers);
        const ctrl = new AbortController();
        const timeoutHandle = bypassTimeout
            ? null
            : setTimeout(() => ctrl.abort(), PROXY_TIMEOUT_MS);

        // Chain the SvelteKit client's disconnect signal into the upstream
        // fetch so closing an admin tab tears down the backend SSE
        // subscription immediately. Without this, the backend's
        // `broadcast::Receiver` + spawned tokio task leak per closed tab
        // until backend restart — every page refresh adds another.
        // `AbortSignal.any` would be cleaner but it's Node 20.3+; chain a
        // listener so we work on older runtimes (vitest's bundled jsdom
        // env included). If the client signal is already aborted (e.g.
        // very fast reload), fire ctrl immediately.
        if (event.request.signal.aborted) {
            ctrl.abort();
        } else {
            event.request.signal.addEventListener('abort', () => ctrl.abort(), {
                once: true
            });
        }
        const init: RequestInit & { duplex?: 'half' } = {
            method: event.request.method,
            headers,
            redirect: 'manual',
            signal: ctrl.signal
        };
        if (event.request.method !== 'GET' && event.request.method !== 'HEAD') {
            init.body = event.request.body;
            // Node's fetch requires `duplex: 'half'` when streaming a
            // request body; otherwise the stream is rejected.
            init.duplex = 'half';
        }

        let upstream: Response;
        try {
            upstream = await fetch(target, init);
        } catch (e) {
            // Network-layer failure (DNS / connection refused / TLS
            // handshake / abort by timeout) — most commonly "backend
            // container restarting". SvelteKit's default 500 would be
            // an HTML page that client.ts can't .json(), which masks
            // the real cause. Emit the standard envelope with a
            // dedicated code instead.
            console.error('Proxy to backend failed:', e);
            if (timeoutHandle) clearTimeout(timeoutHandle);
            return new Response(
                JSON.stringify({
                    error: {
                        code: 'upstream_unavailable',
                        message: 'backend unreachable'
                    }
                }),
                {
                    status: 502,
                    headers: { 'content-type': 'application/json' }
                }
            );
        }

        if (timeoutHandle) clearTimeout(timeoutHandle);
        return new Response(upstream.body, {
            status: upstream.status,
            statusText: upstream.statusText,
            // Strip hop-by-hop headers on the way back too — the upstream's
            // transfer-encoding / content-length / connection headers must
            // not ride along on the re-streamed response.
            headers: stripHopByHopHeaders(upstream.headers)
        });
    }
    return resolve(event);
};
