/**
 * IP Reputation Checking
 * 
 * This module checks if an IP address is safe (residential/user) or suspicious
 * (datacenter/hosting/BOT). Integrate with ipinfo.io or ip-api.com for production use.
 * 
 * Usage:
 * - For ipinfo.io: https://ipinfo.io/{ip}/json
 * - For ip-api.com: http://ip-api.com/json/{ip}
 */

export type IpReputationResult = {
  isSafe: boolean;
  type?: string; // 'residential', 'datacenter', 'hosting', 'bot', 'unknown'
  org?: string;
};

/**
 * Checks IP reputation using an external API
 * 
 * @param clientIp - The client IP address to check
 * @returns Promise with IP reputation result
 * 
 * TODO: Integrate with your preferred IP API service
 * Example implementations provided below
 */
export async function checkIpReputation(clientIp: string | null): Promise<IpReputationResult> {
  if (!clientIp) {
    return { isSafe: false, type: 'unknown' };
  }

  // Skip localhost/internal IPs
  if (
    clientIp === '127.0.0.1' ||
    clientIp === '::1' ||
    clientIp.startsWith('192.168.') ||
    clientIp.startsWith('10.') ||
    clientIp.startsWith('172.16.') ||
    clientIp.startsWith('172.17.') ||
    clientIp.startsWith('172.18.') ||
    clientIp.startsWith('172.19.') ||
    clientIp.startsWith('172.20.') ||
    clientIp.startsWith('172.21.') ||
    clientIp.startsWith('172.22.') ||
    clientIp.startsWith('172.23.') ||
    clientIp.startsWith('172.24.') ||
    clientIp.startsWith('172.25.') ||
    clientIp.startsWith('172.26.') ||
    clientIp.startsWith('172.27.') ||
    clientIp.startsWith('172.28.') ||
    clientIp.startsWith('172.29.') ||
    clientIp.startsWith('172.30.') ||
    clientIp.startsWith('172.31.')
  ) {
    // Local/internal IPs are considered safe for development
    return { isSafe: true, type: 'residential' };
  }

  // TODO: Replace this placeholder with actual API integration
  
  // ============================================
  // OPTION 1: ipinfo.io Integration
  // ============================================
  /*
  try {
    const response = await fetch(`https://ipinfo.io/${clientIp}/json`, {
      headers: {
        'Accept': 'application/json',
      },
    });
    
    if (!response.ok) {
      return { isSafe: false, type: 'unknown' };
    }
    
    const data = await response.json();
    const org = data.org?.toLowerCase() || '';
    
    // Check if IP is from datacenter, hosting, or BOT
    const suspiciousKeywords = [
      'datacenter',
      'data center',
      'hosting',
      'bot',
      'crawler',
      'spider',
      'scraper',
      'proxy',
      'server',
      'cloud',
      'aws',
      'azure',
      'gcp',
      'digitalocean',
      'linode',
      'vultr',
      'hetzner',
      'ovh',
      'google',
      'bing',
      'yandex',
      'baidu',
    ];
    
    const isSuspicious = suspiciousKeywords.some(keyword => org.includes(keyword));
    
    return {
      isSafe: !isSuspicious,
      type: isSuspicious ? 'datacenter' : 'residential',
      org: data.org,
    };
  } catch (error) {
    console.error('Error checking IP reputation with ipinfo.io:', error);
    return { isSafe: false, type: 'unknown' };
  }
  */
  
  // ============================================
  // OPTION 2: ip-api.com Integration
  // ============================================
  /*
  try {
    const response = await fetch(`http://ip-api.com/json/${clientIp}?fields=status,message,org,as,query`, {
      headers: {
        'Accept': 'application/json',
      },
    });
    
    if (!response.ok) {
      return { isSafe: false, type: 'unknown' };
    }
    
    const data = await response.json();
    
    if (data.status === 'fail') {
      return { isSafe: false, type: 'unknown' };
    }
    
    const org = (data.org || '').toLowerCase();
    const as = (data.as || '').toLowerCase();
    
    // Check if IP is from datacenter, hosting, or BOT
    const suspiciousKeywords = [
      'datacenter',
      'data center',
      'hosting',
      'bot',
      'crawler',
      'spider',
      'scraper',
      'proxy',
      'server',
      'cloud',
      'aws',
      'azure',
      'gcp',
      'digitalocean',
      'linode',
      'vultr',
      'hetzner',
      'ovh',
      'google',
      'bing',
      'yandex',
      'baidu',
    ];
    
    const isSuspicious = suspiciousKeywords.some(keyword => 
      org.includes(keyword) || as.includes(keyword)
    );
    
    return {
      isSafe: !isSuspicious,
      type: isSuspicious ? 'datacenter' : 'residential',
      org: data.org,
    };
  } catch (error) {
    console.error('Error checking IP reputation with ip-api.com:', error);
    return { isSafe: false, type: 'unknown' };
  }
  */
  
  // ============================================
  // PLACEHOLDER: Return safe by default
  // Replace with actual API integration above
  // ============================================
  return { isSafe: true, type: 'residential' };
}

