var express = require('express');
var logincontroller = require('../controllers/logincontroller');
var response = require('../controllers/response');

const jwt = require('jsonwebtoken')

var router = express.Router();

router.all("*", async (req, res, next) => {
    try {
        let method = req.originalUrl.split('/').splice(-1,1)[0];
        let result = await AsyncAwaitCaller(method, req.body, logincontroller);
        const token = jwt.sign({
            lid: result.lid
        }, "gohadanchisecretkey");
        res.send(new response({ token: token, user: result }, null));
    } catch (error) {
        res.status(403).send(error);
    }
})

AsyncAwaitCaller = async (method, params, controller) =>  {
    try {
        let result = await controller[method](params);
        return result;
    } catch (error) {
        throw new response(null, error);
    }
}

module.exports = router;