import type { GeoDeviceContext } from '../types.js';

const GEO_DEVICE_URL =
  process.env.GEO_DEVICE_SERVICE_URL ?? 'http://localhost:4002';

export async function fetchGeoContext(
  headers: Record<string, string>,
  body?: unknown,
): Promise<GeoDeviceContext | null> {
  try {
    const url = `${GEO_DEVICE_URL}/api/context`;
    const options: RequestInit = {
      method: body ? 'POST' : 'GET',
      headers: {
        'Content-Type': 'application/json',
        'user-agent': headers['user-agent'] ?? '',
        'accept-language': headers['accept-language'] ?? '',
        'x-forwarded-for': headers['x-forwarded-for'] ?? '',
        'x-real-ip': headers['x-real-ip'] ?? '',
      },
    };
    if (body) {
      options.body = JSON.stringify(body);
    }
    const res = await fetch(url, options);
    if (!res.ok) return null;
    return (await res.json()) as GeoDeviceContext;
  } catch {
    return null;
  }
}
