import jwt from 'jsonwebtoken';

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

const userDoesNotExist = async (req, res, next) => {

    const { username } = req.body;

    if (await UserService.exists(username)) {
        return res.status(401).send("Such user exists!");
    }
    next();
};

const userExist = async (req, res, next) => {
    let username;
    if (req.body.username) {
        username = req.body.username;
    } else if (req.cookies["jwt"]) {
        if (!req.cookies["jwt"] || !jwt.verify(req.cookies["jwt"], config.secret)) {
            return res.status(403).send("Unauthorized");
        }
        username = jwt.decode(req.cookies["jwt"]).username;
    }

    if (!(await UserService.exists(username))) {
        return res.status(401).send("Such user does not exists!");
    }
    next();
}

export default {userDoesNotExist, userExist};