const crypto = require('crypto');

// token -> { username, isAdmin, expiresAt }
const tokenStore = new Map();

function generateToken() {
    return crypto.randomBytes(48).toString('hex');
}

function createSession(username, isAdmin) {
    const token = generateToken();
    const expiresAt = Date.now() + 60 * 60 * 1000; // 1 heure

    tokenStore.set(token, {
        username,
        isAdmin,
        expiresAt
    });

    return { token, expiresAt };
}

function verifyToken(req, res, next) {
    const token = req.headers['x-access-token'];

    if (!token) {
        return res.status(401).send("Missing token");
    }

    const session = tokenStore.get(token);

    if (!session) {
        return res.status(401).send("Invalid token");
    }

    if (Date.now() > session.expiresAt) {
        tokenStore.delete(token);
        return res.status(401).send("Token expired");
    }

    req.user = {
        username: session.username,
        isAdmin: session.isAdmin
    };

    next();
}

// nettoyage automatique
setInterval(() => {
    const now = Date.now();

    for (const [token, session] of tokenStore.entries()) {
        if (now > session.expiresAt) {
            tokenStore.delete(token);
        }
    }
}, 10 * 60 * 1000);

module.exports = {
    createSession,
    verifyToken
};