/**
 * User-Agent Parser Module
 * Extracts device type, OS, and browser information from User-Agent strings
 */

function parseUserAgent(userAgent) {
    if (!userAgent) {
        return {
            deviceType: 'unknown',
            os: 'unknown',
            browser: 'unknown'
        };
    }

    const ua = userAgent.toLowerCase();

    // Detect OS
    let os = 'other';
    if (ua.includes('android')) {
        os = 'android';
    } else if (ua.includes('iphone') || ua.includes('ipad') || ua.includes('ipod')) {
        os = 'ios';
    } else if (ua.includes('windows')) {
        os = 'windows';
    } else if (ua.includes('mac os')) {
        os = 'macos';
    } else if (ua.includes('linux') && !ua.includes('android')) {
        os = 'linux';
    } else if (ua.includes('cros')) {
        os = 'chromeos';
    }

    // Detect Device Type
    let deviceType = 'desktop';
    if (ua.includes('mobile') || (ua.includes('android') && !ua.includes('tablet'))) {
        deviceType = 'mobile';
    } else if (ua.includes('tablet') || ua.includes('ipad')) {
        deviceType = 'tablet';
    }

    // Detect Browser (order matters - check specific browsers first)
    let browser = 'other';
    if (ua.includes('edg/') || ua.includes('edge/')) {
        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';
    }

    return { deviceType, os, browser };
}

module.exports = { parseUserAgent };
