export interface RequestContextLike {
  headers?: Record<string, string | string[] | undefined> | undefined;
  ip?: string | undefined;
  connection?: { remoteAddress?: string | undefined } | undefined;
  socket?: { remoteAddress?: string | undefined } | undefined;
}

export function extractClientIp(request?: RequestContextLike): string {
  if (!request) return "unknown";

  const forwarded = request.headers?.["x-forwarded-for"];
  const forwardedIp = Array.isArray(forwarded) ? forwarded[0] : forwarded;
  const rawIp =
    (typeof forwardedIp === "string" ? forwardedIp.split(",")[0]?.trim() : undefined) ||
    (typeof request.headers?.["x-real-ip"] === "string"
      ? request.headers["x-real-ip"]
      : undefined) ||
    request.connection?.remoteAddress ||
    request.socket?.remoteAddress ||
    request.ip ||
    "unknown";

  return rawIp.replace(/^::ffff:/, "");
}

export function extractUserAgent(request?: RequestContextLike): string | undefined {
  const uaHeader = request?.headers?.["user-agent"];
  return Array.isArray(uaHeader) ? uaHeader[0] : uaHeader;
}
