// Server-side helper: all backend calls go through the Rust gateway.
// Read from process.env (not import.meta.env) since this is server-only code and the
// gateway URL differs per environment (k8s service DNS) — it must be resolved at
// runtime, not baked in at build time.
const GATEWAY_URL = (process.env.GATEWAY_URL || 'http://localhost:9100').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.
 * Extra headers (e.g. Content-Type: multipart/form-data for file uploads) take precedence
 * over the default application/json.
 */
export function withAuthHeaders(
  request: Request,
  extra: Record<string, string> = {},
): Record<string, string> {
  return {
    ...forwardAuth(request),
    ...forwardCookies(request),
    ...extra,
    // Default Content-Type only if extra didn't already provide one
    ...(extra['Content-Type'] ? {} : { 'Content-Type': 'application/json' }),
  };
}
