const db = require('./database');

module.exports = app => {
    const routes = require('../methods/routes');

    const paths = routes.map(route => route.url);

    app.use(paths, async function(request, response, next) {
        try {
            const token = getToken(request);
            const query = `SELECT at.id, at.userId, eu.email, u.lang, at.ttl, at.created
                                FROM salix.AccessToken at
                                    JOIN account.user u ON u.id = at.userid
                                    JOIN account.emailUser eu ON eu.userFk = u.id
                            WHERE at.id = ?`;

            const auth = await db.findOne(query, [token]);

            if (!auth || isTokenExpired(auth.created, auth.ttl))
                throw new Error('Invalid authorization token');

            const args = Object.assign({}, request.query);
            const props = Object.assign(args, request.body);
            props.authorization = auth.id;

            response.locals = props;
            response.locals.auth = {
                userId: auth.userId,
                token: auth.id,
                email: auth.email,
                locale: auth.lang
            };

            next();
        } catch (error) {
            next(error);
        }
    });

    // Register routes
    for (let route of routes)
        app.use(route.url, route.cb);

    function getToken(request) {
        const headers = request.headers;
        const queryParams = request.query;

        return headers.authorization || queryParams.authorization;
    }

    function isTokenExpired(created, ttl) {
        const date = new Date(created);
        const currentDate = new Date();

        date.setSeconds(date.getSeconds() + ttl);

        if (currentDate > date)
            return true;

        return false;
    }
};