/**
 * One call that turns "a socket handshake + a pre-chat form" into everything
 * the agent sees in the profile panel before the first message arrives.
 */
import { clientIp } from './ip.js';
import { lookupGeo, type GeoInfo } from './geo.js';
import { parseUserAgent, type DeviceInfo } from './device.js';

export interface EnrichmentInput {
  headers: Record<string, any>;
  socket?: { remoteAddress?: string };
  /** Client-reported extras from the widget (never trusted for auth). */
  clientHints?: {
    locale?: string;
    timezone?: string;
    screen?: { w: number; h: number; dpr: number };
    pageUrl?: string;
    referrer?: string;
  };
}

export interface Enrichment {
  ip: string;
  userAgent: string;
  device: DeviceInfo;
  geo: GeoInfo;
  locale?: string;
  timezone?: string;
  screen?: { w: number; h: number; dpr: number };
  pageUrl?: string;
  referrer?: string;
}

export async function enrich(input: EnrichmentInput): Promise<Enrichment> {
  const ip = clientIp(input as any);
  const userAgent = String(input.headers['user-agent'] ?? '');
  const acceptLang = String(input.headers['accept-language'] ?? '');

  const [geo] = await Promise.all([lookupGeo(ip)]);

  return {
    ip,
    userAgent,
    device: parseUserAgent(userAgent),
    geo,
    locale: input.clientHints?.locale || acceptLang.split(',')[0] || undefined,
    timezone: input.clientHints?.timezone,
    screen: input.clientHints?.screen,
    pageUrl: input.clientHints?.pageUrl,
    referrer: input.clientHints?.referrer || String(input.headers['referer'] ?? '') || undefined,
  };
}

export { formatGeo } from './geo.js';
export { formatDevice } from './device.js';
export type { GeoInfo, DeviceInfo };
