/**
 * Parse user agent string to extract device, browser, and OS information
 * Simple parser without external dependencies
 */

export interface ParsedUserAgent {
  deviceType: 'WEB' | 'MOBILE' | 'TABLET' | 'UNKNOWN';
  browser: string;
  os: string;
  raw: string;
}

/**
 * Parse user agent string to extract device, browser, and OS
 */
export function parseUserAgent(userAgent: string | null | undefined): ParsedUserAgent {
  if (!userAgent) {
    return {
      deviceType: 'UNKNOWN',
      browser: 'Unknown',
      os: 'Unknown',
      raw: ''
    };
  }

  const ua = userAgent.toLowerCase();
  
  // Detect device type
  let deviceType: 'WEB' | 'MOBILE' | 'TABLET' | 'UNKNOWN' = 'WEB';
  if (/tablet|ipad|playbook|silk/i.test(userAgent)) {
    deviceType = 'TABLET';
  } else if (/mobile|iphone|ipod|android|blackberry|opera|mini|windows\s+phone|palm|iemobile/i.test(userAgent)) {
    deviceType = 'MOBILE';
  }

  // Detect browser
  let browser = 'Unknown';
  if (ua.includes('edg/')) {
    browser = 'Edge';
  } else if (ua.includes('chrome/') && !ua.includes('edg/')) {
    browser = 'Chrome';
  } else if (ua.includes('firefox/')) {
    browser = 'Firefox';
  } else if (ua.includes('safari/') && !ua.includes('chrome/')) {
    browser = 'Safari';
  } else if (ua.includes('opera/') || ua.includes('opr/')) {
    browser = 'Opera';
  } else if (ua.includes('msie') || ua.includes('trident/')) {
    browser = 'Internet Explorer';
  }

  // Detect OS
  let os = 'Unknown';
  if (ua.includes('windows nt')) {
    if (ua.includes('windows nt 10.0')) {
      os = 'Windows 10/11';
    } else if (ua.includes('windows nt 6.3')) {
      os = 'Windows 8.1';
    } else if (ua.includes('windows nt 6.2')) {
      os = 'Windows 8';
    } else if (ua.includes('windows nt 6.1')) {
      os = 'Windows 7';
    } else {
      os = 'Windows';
    }
  } else if (ua.includes('mac os x') || ua.includes('macintosh')) {
    os = 'macOS';
  } else if (ua.includes('linux')) {
    os = 'Linux';
  } else if (ua.includes('android')) {
    os = 'Android';
  } else if (ua.includes('iphone') || ua.includes('ipad')) {
    os = 'iOS';
  } else if (ua.includes('ipod')) {
    os = 'iOS';
  }

  return {
    deviceType,
    browser,
    os,
    raw: userAgent
  };
}

