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

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

dotenv.config({path: ".env"});

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

const validateInviteToken = async (req, res, next) => {
    if (process.env.REQUIRE_TOKEN != "true") 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};