const useragent = require('useragent');
const crypto = require('crypto');
const geoip = require('geoip-lite');
const axios = require('axios'); 

function getTimeBucket(hour) {
    if (hour >= 6 && hour < 12) return "Morning";
    if (hour >= 12 && hour < 18) return "Afternoon";
    if (hour >= 18 && hour < 24) return "Evening";
    return "Night";
}

function hashUserId(uid) {
    return crypto.createHash('sha256').update(uid).digest('hex');
}

async function extractSignals(req) {
    const agent = useragent.parse(req.headers['user-agent'] || '');
    const hour = new Date().getHours();

    const rawUserId = req.query.userId;

    if (!rawUserId) {
        return { userId: null };
    }

    // 1. ✅ Extract IP safely (supports proxies)
    // 🚀 LIVE HOSTING FIX: Look through common shared hosting headers first
    const ip =
        req.headers['x-forwarded-for']?.split(',')[0].trim() ||
        req.headers['x-real-ip'] ||
        req.headers['cf-connecting-ip'] || // In case Namecheap uses Cloudflare routing
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        null;

    let country = "Unknown";

    // 2. PRIMARY CHOICE: Live API Lookup (Handles modern routing/VPN changes instantly)
    if (ip && ip !== '::1' && ip !== '127.0.0.1') {
        try {
            // Corrected API URL format for axios
            const response = await axios.get(`http://ip-api.com{ip}?fields=countryCode`, { timeout: 2000 });
            if (response.data && response.data.countryCode) {
                country = response.data.countryCode; // Returns "KE", "GB", etc.
            }
        } catch (err) {
            country = "Unknown"; 
        }
    }

    // 3. FALLBACK CHOICE: If API fails or is Unknown, fall back to local geoip-lite
    if (country === "Unknown" && ip) {
        const geo = geoip.lookup(ip);
        if (geo && geo.country) {
            country = geo.country; 
        }
    }

    return {
        userId: hashUserId(rawUserId),
        userAgentCategory: `${agent.family}-${agent.os.family}`,
        country: country,
        timeBucket: getTimeBucket(hour),
        timestamp: new Date()
    };
}

module.exports = { extractSignals };