// Server-side helper: all backend calls go through the Rust gateway
const GATEWAY_URL = (process.env.GATEWAY_URL || 'http://localhost:8000').replace(/\/+$/, '');

export function gatewayUrl(path: string): string {
  const normalized = path.startsWith('/') ? path : `/${path}`;
  return `${GATEWAY_URL}${normalized}`;
}

/** Forward the Authorization header from an incoming browser request to the gateway */
export function forwardAuth(request: Request): Record<string, string> {
  const auth = request.headers.get('Authorization');
  return auth ? { Authorization: auth } : {};
}

/** Forward the Cookie header from an incoming browser request to the gateway */
export function forwardCookies(request: Request): Record<string, string> {
  const cookie = request.headers.get('cookie');
  return cookie ? { cookie } : {};
}

/**
 * Merge auth + cookie headers from the incoming request with any extra headers provided.
 */
export function withAuthHeaders(
  request: Request,
  extra: Record<string, string> = {},
): Record<string, string> {
  return {
    'Content-Type': 'application/json',
    ...forwardAuth(request),
    ...forwardCookies(request),
    ...extra,
  };
}
