const express = require('express');
const router = express.Router();

const {
    getOrCreateUser,
    isInLearning,
    isKnownPrimary,
    createSignature,
    updateSecondarySignals,
    incrementPending,
    promoteIfEligible,
    finalizeEvent
} = require('../services/baselineService');

const { computeRisk } = require('../services/anomalyService');
const { sendAlert } = require('../services/alertService');

const Event = require('../models/Event');
const { extractSignals } = require('../services/signalService');

router.get('/', async (req, res) => {
    
    // ✅ PREVENT IMAGE CACHING (PLACE IT HERE)
    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    res.set('Pragma', 'no-cache');
    res.set('Expires', '0');
    
    try {

    const signal = await extractSignals(req);
    
    if (!signal.userId) {
    return res.status(400).send("userId is required");
}

    const user = await getOrCreateUser(signal.userId);

    let risk = 0;
    let reasons = [];
    let isAnomalous = false;

    const learning = await isInLearning(user);

    const primaryKnown = await isKnownPrimary(signal, user);

    const signature = createSignature(signal);

    if (learning) {

        // ✅ During learning, directly trust
        const { BloomFilter } = require('bloom-filters');
        const filter = BloomFilter.fromJSON(user.bloomFilter);
        filter.add(signature);
        user.bloomFilter = filter.saveAsJSON();

    } else {

        const result = computeRisk(signal, user, primaryKnown);

        risk = result.risk;
        reasons = result.reasons;

        isAnomalous = risk >= 60;

        if (!primaryKnown) {
            await incrementPending(user, signature);
            await promoteIfEligible(user, signature, risk);
        }
        

        if (isAnomalous) {
            await sendAlert(
                `⚠️ Suspicious email access\nRisk: ${risk}\nReasons: ${reasons.join(", ")}`
            );
        }
        console.log("Risk:", risk, "Reasons:", reasons);
    }

    await updateSecondarySignals(user, signal);
    await finalizeEvent(user);

    await Event.create({
        userId: signal.userId,
        userAgentCategory: signal.userAgentCategory,
        country: signal.country,
        timeBucket: signal.timeBucket,
        riskScore: risk,
        reasons,
        isAnomalous
    });

    const pixel = Buffer.from(
        "R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",
        "base64"
    );

    res.set('Content-Type', 'image/gif');
    res.send(pixel);
    
    } catch (err) {
        console.error("Track route error:", err);
        res.status(500).send("Internal server error");
    }
});

module.exports = router;