import { isIP } from 'node:net';
import type { Request } from 'express';

export interface DeviceInfo {
  robot: boolean;
  device: string;
  browser: string;
  isRobot: boolean;
  hostname: string;
  platform: string;
  deviceType: string;
  ip_address: string;
  user_agent: string;
  lat: number | null;
  lng: number | null;
}

/**
 * Express resolves req.ip from X-Forwarded-For only when the app trusts its
 * reverse proxy. This keeps client-supplied forwarded headers from being used
 * directly when the API is accessed without Apache/Nginx.
 */
export function getClientIp(req?: Request): string | null {
  if (!req) {
    return null;
  }

  // Cloudflare supplies the original visitor address in this header. Only
  // trust it when the deployment explicitly opts into Cloudflare proxying.
  if (process.env.TRUST_CLOUDFLARE?.trim().toLowerCase() === 'true') {
    const cloudflareIp = req.headers['cf-connecting-ip'];
    const rawCloudflareIp = Array.isArray(cloudflareIp)
      ? cloudflareIp[0]
      : cloudflareIp;
    const normalizedCloudflareIp = rawCloudflareIp
      ?.replace(/^::ffff:/i, '')
      .trim();

    if (normalizedCloudflareIp && isIP(normalizedCloudflareIp) !== 0) {
      return normalizedCloudflareIp;
    }
  }

  const rawIp = req.ip || req.socket?.remoteAddress;
  if (!rawIp) {
    return null;
  }

  // Normalize IPv6-mapped IPv4 addresses such as ::ffff:192.168.1.217.
  const ipAddress = rawIp.replace(/^::ffff:/i, '').trim();
  return isIP(ipAddress) === 0 ? null : ipAddress;
}

export function parseDeviceInfo(
  req?: Request,
  providedLat?: number,
  providedLng?: number,
): DeviceInfo {
  const lat = typeof providedLat === 'number' && !Number.isNaN(providedLat) ? providedLat : null;
  const lng = typeof providedLng === 'number' && !Number.isNaN(providedLng) ? providedLng : null;

  if (!req) {
    return {
      robot: false,
      device: 'Unknown',
      browser: 'Unknown',
      isRobot: false,
      hostname: 'Unknown',
      platform: 'Unknown',
      deviceType: 'Desktop',
      ip_address: 'Unknown',
      user_agent: 'Unknown',
      lat,
      lng,
    };
  }

  const userAgent = (req.headers['user-agent'] as string) || '';
  const ip_address = getClientIp(req) ?? 'Unknown';
  const hostname =
    req.hostname || (req.headers['host'] as string) || 'localhost';

  let browser = 'Unknown';
  let device = 'Desktop';
  let platform = 'Unknown';
  let deviceType = 'Desktop';
  let isRobot = false;

  const ua = userAgent.toLowerCase();

  // Detect bots / robots
  if (
    /bot|crawler|spider|crawling|googlebot|bingbot|slurp|duckduckbot|baiduspider|yandexbot/i.test(
      userAgent,
    )
  ) {
    isRobot = true;
  }

  // Detect Device Type
  if (/mobile|iphone|ipod|android.*mobile|windows phone/i.test(ua)) {
    deviceType = 'Mobile';
  } else if (/ipad|android(?!.*mobile)|tablet/i.test(ua)) {
    deviceType = 'Tablet';
  } else {
    deviceType = 'Desktop';
  }

  // Detect Platform / OS & Device
  if (/macintosh|mac os x/i.test(userAgent)) {
    device = 'Macintosh';
    const match = userAgent.match(/Mac OS X ([0-9_]+)/);
    platform = match ? `OS X ${match[1]}` : 'macOS';
  } else if (/windows/i.test(userAgent)) {
    device = 'Windows PC';
    const match = userAgent.match(/Windows NT ([0-9.]+)/);
    platform = match ? `Windows NT ${match[1]}` : 'Windows';
  } else if (/iphone|ipad|ipod/i.test(userAgent)) {
    device = /ipad/i.test(userAgent) ? 'iPad' : 'iPhone';
    const match = userAgent.match(/OS ([0-9_]+) like Mac OS X/);
    platform = match ? `iOS ${match[1].replace(/_/g, '.')}` : 'iOS';
  } else if (/android/i.test(userAgent)) {
    device = 'Android Device';
    const match = userAgent.match(/Android ([0-9.]+)/);
    platform = match ? `Android ${match[1]}` : 'Android';
  } else if (/linux/i.test(userAgent)) {
    device = 'Linux';
    platform = 'Linux';
  }

  // Detect Browser Name & Version
  if (/edg\/([0-9.]+)/i.test(userAgent)) {
    const match = userAgent.match(/Edg\/([0-9.]+)/i);
    browser = `Edge ${match ? match[1] : ''}`.trim();
  } else if (/chrome\/([0-9.]+)/i.test(userAgent) && !/edg/i.test(userAgent)) {
    const match = userAgent.match(/Chrome\/([0-9.]+)/i);
    browser = `Chrome ${match ? match[1] : ''}`.trim();
  } else if (/firefox\/([0-9.]+)/i.test(userAgent)) {
    const match = userAgent.match(/Firefox\/([0-9.]+)/i);
    browser = `Firefox ${match ? match[1] : ''}`.trim();
  } else if (/safari\/([0-9.]+)/i.test(userAgent) && !/chrome/i.test(userAgent)) {
    const match = userAgent.match(/Version\/([0-9.]+)/i);
    browser = `Safari ${match ? match[1] : ''}`.trim();
  } else if (userAgent.length > 0) {
    browser = userAgent.split(' ')[0] || 'Unknown';
  }

  return {
    robot: isRobot,
    device,
    browser,
    isRobot,
    hostname,
    platform,
    deviceType,
    ip_address,
    user_agent: userAgent,
    lat,
    lng,
  };
}
