import type { Request } from 'express';

export function resolveClientIp(req: Pick<Request, 'ip' | 'headers'>): string | undefined {
  const forwarded = req.headers['x-forwarded-for'];
  if (typeof forwarded === 'string') {
    const first = forwarded.split(',')[0]?.trim();
    if (first) return first;
  }
  if (Array.isArray(forwarded)) {
    const first = forwarded[0]?.trim();
    if (first) return first;
  }

  const realIp = req.headers['x-real-ip'];
  if (typeof realIp === 'string' && realIp.trim()) {
    return realIp.trim();
  }

  const ip = req.ip?.replace(/^::ffff:/, '').trim();
  return ip || undefined;
}

export function resolveClientUserAgent(req: Pick<Request, 'headers'>): string | undefined {
  const value = req.headers['user-agent'];
  if (typeof value !== 'string') return undefined;
  const trimmed = value.trim();
  return trimmed || undefined;
}

export function enrichAuthClientMeta<T extends object>(req: Pick<Request, 'ip' | 'headers'>, dto: T) {
  return {
    ...dto,
    ipAddress: resolveClientIp(req),
    userAgent: resolveClientUserAgent(req)
  };
}
