import fs from 'fs';
import jwt from 'jsonwebtoken';

import UserService from '../services/user.js';
import config from '../config.js';


const authenticate = async (req, res, next) => {
    try {
        const token = req.cookies["jwt"];
        if (!token || !jwt.verify(token, config.secret)) {
            req.session.destroy();
            res.clearCookie("jwt");
            return res.redirect("/login");
        }
        next();
    } catch(e) {
        console.log(e)
	req.session.destroy();
        res.clearCookie("jwt");
        return res.redirect("/login");
    }
};

const validateInviteToken = async (req, res, next) => {
    if (!config.require_token) return next();

    const { inviteToken } = req.body;
    if (!inviteToken || inviteToken == "") return res.status(400).send("Token is not valid");
    fs.appendFileSync('./inviteTokens.txt', '');
    const inviteTokens = fs.readFileSync('./inviteTokens.txt').toString().split('\n');
    let tokenValid = false;

    inviteTokens.forEach((token) => {
        if (token == inviteToken) tokenValid = true;
    });

    if (!tokenValid) return res.status(400).send("Token is not valid");
    next();
};

const canHaveCloak = async (req, res, next) => {
    const { username } = jwt.decode(req.cookies["jwt"]);
    if (!(await UserService.canHaveCloak(username)))
        return res.status(403).send("You cannot have cloak");
    next();
}

export default {authenticate, validateInviteToken, canHaveCloak};
