import { Router } from 'express';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

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

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

const UserRouter = new Router();

UserRouter.get('/register', async (req, res) => {
    if (req.session.jwt && jwt.verify(req.session.jwt, process.env.SECRET))
        return res.redirect("/index");

    return res.render("register.pug", {
        require_token: process.env.REQUIRE_TOKEN == "true"? true : false
    });
});

UserRouter.get(['/', '/login'], async (req, res) => {
    if(req.session.jwt && jwt.verify(req.session.jwt, process.env.SECRET)) {
        return res.redirect("/index");
    }

    return res.render("login.pug");
});

UserRouter.get('/index', auth.authenticate, async (req, res) => {
    if (!req.session.jwt || !jwt.verify(req.session.jwt, process.env.SECRET))
        return res.redirect("/login");
    
    const decoded = jwt.decode(req.session.jwt);

    return res.render('index.pug', {
        username: decoded.username,
        can_have_cloak: await UserService.canHaveCloak(decoded.username)
    });
})

export default UserRouter;