const { BloomFilter } = require('bloom-filters');
const UserBaseline = require('../models/UserBaseline');

const LEARNING_EVENTS = 55; // Change to 55 for thesis

function createSignature(signal) {
    return `${signal.country}-${signal.userAgentCategory}`;
}

async function getOrCreateUser(userId) {
    let user = await UserBaseline.findOne({ userId });

    if (!user) {
        const filter = BloomFilter.create(500, 0.01);

        user = await UserBaseline.create({
            userId,
            bloomFilter: filter.saveAsJSON()
        });
    }

    return user;
}

async function updateSecondarySignals(user, signal) {

    user.userAgentCounts.set(
        signal.userAgentCategory,
        (user.userAgentCounts.get(signal.userAgentCategory) || 0) + 1
    );

    user.countryCounts.set(
        signal.country,
        (user.countryCounts.get(signal.country) || 0) + 1
    );

    user.timeBucketCounts.set(
        signal.timeBucket,
        (user.timeBucketCounts.get(signal.timeBucket) || 0) + 1
    );

    user.lastEventAt = signal.timestamp;

    // ✅ Burst tracking
    user.recentOpens.push({ timestamp: signal.timestamp });

    const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);

    user.recentOpens = user.recentOpens.filter(
        entry => entry.timestamp > twentyFourHoursAgo
    );

    user.averageHourlyOpens = user.recentOpens.length / 24;
}

async function incrementPending(user, signature) {

    const count = user.pendingSignatures.get(signature) || 0;
    user.pendingSignatures.set(signature, count + 1);
}

async function promoteIfEligible(user, signature, risk) {

    const count = user.pendingSignatures.get(signature) || 0;

    // ✅ Safe side ≥10
    if (count >= 10 && risk < 40) {

        const filter = BloomFilter.fromJSON(user.bloomFilter);
        filter.add(signature);

        user.bloomFilter = filter.saveAsJSON();
        user.pendingSignatures.delete(signature);

        console.log("✅ Signature promoted to trusted baseline:", signature);
    }
}

async function finalizeEvent(user) {
    user.totalEvents += 1;
    await user.save();
}

async function isInLearning(user) {
    return user.totalEvents < LEARNING_EVENTS;
}

async function isKnownPrimary(signal, user) {
    const filter = BloomFilter.fromJSON(user.bloomFilter);
    return filter.has(createSignature(signal));
}

module.exports = {
    getOrCreateUser,
    isInLearning,
    isKnownPrimary,
    createSignature,
    updateSecondarySignals,
    incrementPending,
    promoteIfEligible,
    finalizeEvent
};