import { CORRELATION_ID_HEADER } from "@/lib/correlation-id";

const CORE_API = process.env.CORE_API_URL || "http://localhost:4000";

export interface UpstreamOptions extends RequestInit {
  correlationId?: string;
}

export async function fetchUpstream(
  path: string,
  options: UpstreamOptions = {},
): Promise<Response | null> {
  const { correlationId, headers: initHeaders, ...fetchOptions } = options;
  const headers = new Headers(initHeaders);

  if (correlationId) {
    headers.set(CORRELATION_ID_HEADER, correlationId);
  }

  try {
    return await fetch(`${CORE_API}${path}`, { ...fetchOptions, headers });
  } catch {
    return null;
  }
}
