import { getEnv } from './env.js';
/**
 * Detect the public-facing base URL from request headers.
 *
 * On cloud GPU platforms (RunPod, Vast.ai, etc.), the application runs behind
 * a reverse proxy that sets forwarding headers. This function reads those
 * headers to determine the URL that the user's browser is actually accessing,
 * so that Stripe callbacks, magic link emails, and cookie settings use the
 * correct public URL instead of the internal localhost address.
 *
 * Priority order:
 *   1. X-Forwarded-Proto + X-Forwarded-Host (standard reverse proxy headers)
 *   2. Origin header (sent by browsers on POST/CORS requests)
 *   3. Referer header (fallback — contains the page URL)
 *   4. DASHBOARD_URL env var (internal default: http://127.0.0.1:3367)
 *
 * Returns a base URL with no trailing slash, e.g.:
 *   "https://abc123-3367.proxy.runpod.net"
 *   "http://localhost:3367"
 */
export function getPublicBaseUrl(c) {
    // 1. Standard reverse proxy headers (most reliable)
    const forwardedHost = c.req.header('x-forwarded-host');
    const forwardedProto = c.req.header('x-forwarded-proto') || 'https';
    if (forwardedHost) {
        const host = forwardedHost.split(',')[0].trim(); // Take first if multiple
        return `${forwardedProto}://${host}`;
    }
    // 2. Origin header (browsers send this on POST and CORS requests)
    const origin = c.req.header('origin');
    if (origin && origin !== 'null' && origin.startsWith('http')) {
        return origin.replace(/\/$/, '');
    }
    // 3. Referer header (contains full URL of the page making the request)
    const referer = c.req.header('referer');
    if (referer && referer.startsWith('http')) {
        try {
            const url = new URL(referer);
            return `${url.protocol}//${url.host}`;
        }
        catch {
            // Invalid referer URL, skip
        }
    }
    // 4. Host header with protocol detection
    const host = c.req.header('host');
    if (host && !host.startsWith('127.0.0.1') && !host.startsWith('localhost')) {
        // External host — likely behind a proxy, assume HTTPS
        const proto = c.req.header('x-forwarded-proto') || 'https';
        return `${proto}://${host}`;
    }
    // 5. Fallback: DASHBOARD_URL env var (internal localhost default)
    return getEnv().DASHBOARD_URL;
}
/**
 * Get the cancel URL for Stripe checkout, using the detected public URL.
 */
export function getCheckoutCancelUrl(c) {
    return `${getPublicBaseUrl(c)}/dashboard?checkout=cancelled`;
}
/**
 * Determine if the current request is coming over HTTPS
 * (for secure cookie settings).
 */
export function isSecureRequest(c) {
    const url = getPublicBaseUrl(c);
    return url.startsWith('https://');
}
//# sourceMappingURL=public-url.js.map