/**
 * Request Geo Helpers
 *
 * Every subscription/payment route needs the same two things: the buyer's real
 * IP and — because the Next.js `rewrites()` proxy hides that IP behind a
 * loopback address — the client-detected country hint. These were duplicated
 * inline in each route; keep the extraction in one place so display pricing and
 * the actual charge always resolve the region the same way.
 */

import { Request } from 'express';

/** Client IP, preferring proxy headers over the socket address. */
export function getClientIp(req: Request): string {
  return (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim()
    || (req.headers['x-real-ip'] as string)
    || req.socket.remoteAddress
    || '127.0.0.1';
}

/**
 * Client-detected country hint (2-letter code), or null when absent/malformed.
 *
 * Accepted, in priority order:
 *   - `X-Country-Code` header — sent by the frontend on every API call
 *   - `?countryCode=` query param — used by the public pricing endpoints
 *   - `countryCode` in the JSON body — POST/PUT payment calls
 *
 * This is only ever a *hint*: the backend still prefers its own IP lookup
 * whenever the request carries a real public address.
 */
export function getCountryHint(req: Request): string | null {
  const candidates = [
    req.headers['x-country-code'],
    req.query?.countryCode,
    (req.body as Record<string, unknown> | undefined)?.countryCode,
  ];

  for (const candidate of candidates) {
    const value = Array.isArray(candidate) ? candidate[0] : candidate;
    if (typeof value === 'string' && /^[A-Za-z]{2}$/.test(value.trim())) {
      return value.trim().toUpperCase();
    }
  }
  return null;
}
