import type { Request } from 'express';

/**
 * 프록시/LB 환경 고려:
 * - app.set('trust proxy', true) 또는 enable('trust proxy')가 설정되면 req.ip 신뢰 가능
 * - 그렇지 않으면 x-forwarded-for를 직접 파싱
 */
export function extractClientIp(req: Request): string {
  const xff = req.headers['x-forwarded-for'];

  if (typeof xff === 'string' && xff.length > 0) {
    // "client, proxy1, proxy2" 형태일 수 있음 → 첫 번째가 원 IP
    return xff.split(',')[0].trim();
  }

  // Express가 trust proxy 설정 시 적절히 계산한 값
  if (req.ip) return req.ip;

  // 최후 fallback
  return (req.socket?.remoteAddress ?? '').toString();
}
