import {userService} from '../services/userService.js'

function register(req, res) {

    let username = req.body.username;
    let firstname = req.body.firstname;
    let lastname = req.body.lastname;
    let email = req.body.email;
    let password = req.body.password;
    userService.register(username, firstname, lastname, email, password)
        .then(result => {
            if (result === true) {
                res.render('login');
            }  else {
                res.render('register');
            }
        });
}


function login(req, res) {
    let username = req.body.username;
    let password = req.body.password;
    userService.login(username, password)
        .then(result => {
            if (result.token) {
                res.cookie('Jwt', result.token, {
                   httpOnly: true,
                   maxAge: 60*60*24*1000,
                });
                res.redirect('/dashboard');
            } else {
                res.render('login');
            }
        });
}

function signout(req, res) {
    if (req.cookies.Jwt) {
        res.clearCookie('Jwt');
    }
    res.redirect('/login');
}

export default {login, register, signout}