var express = require('express');
const { UniqueConstraintError } = require('sequelize/dist/index.js');
var router = express.Router();
const db = require('../models');
var User = db.User;
const crypto = require('crypto');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('login', { title: 'Express' });
});

router.post('/', async function(req, res, next) {
  console.log(req.body);
  var user = await User.findOne({
    where: {
      email: req.body.email,
      password: req.body.password
    }
  });
  console.log(user);
  if(user) {
    var uuid = crypto.randomUUID();
    var agentid = req.rawHeaders[3];
    var session = await user.createSession({
      sessionid: uuid,
      agentid: agentid
    });
    console.log(session);
    var maxage = 60 * 60 * 24;
    res.cookie('sessionid', session.sessionid, {maxAge: maxage, httpOnly: true});
    res.redirect('/');
  } else {
    res.render('login');
  }  
});

module.exports = router;
