import type { IncomingMessage } from 'http';

export function getBaseUrl(req: IncomingMessage): string {
  const forwarded = req.headers['x-forwarded-proto'];
  const protoHeader = Array.isArray(forwarded) ? forwarded[0] : forwarded;
  const proto = protoHeader?.split(',')[0]?.trim() || 'http';
  const host = req.headers.host || 'localhost:3000';
  return `${proto}://${host}`;
}

export async function fetchFromApi<T>(req: IncomingMessage, path: string): Promise<T | null> {
  try {
    const response = await fetch(`${getBaseUrl(req)}${path}`);
    if (!response.ok) return null;
    return (await response.json()) as T;
  } catch {
    return null;
  }
}
