import { buildEngineUpstreamHeaders } from '@/lib/engine-upstream-headers';

export function engineBaseUrl(): string {
  return process.env['SCRIBA_ENGINE_URL']?.trim() || 'http://localhost:3100';
}

export async function fetchEngine(
  path: string,
  init: RequestInit & { rawBody?: string } = {},
): Promise<Response> {
  const method = (init.method ?? 'GET').toUpperCase();
  const url = `${engineBaseUrl()}/scriba/${path.replace(/^\//, '')}`;
  const upstream = buildEngineUpstreamHeaders(method, {
    rawBody: init.rawBody,
    jsonBody:
      init.rawBody === undefined && init.body && typeof init.body === 'string' && init.headers
        ? (() => {
            try {
              return JSON.parse(init.body as string) as Record<string, unknown>;
            } catch {
              return undefined;
            }
          })()
        : undefined,
  });

  const { rawBody: _raw, ...rest } = init;
  return fetch(url, {
    ...rest,
    headers: {
      ...upstream,
      ...(init.headers as Record<string, string> | undefined),
    },
    cache: 'no-store',
  });
}
