const directory = require('../api2/directory');

module.exports = () => (req, res, next) => {
    let { code } = req.query;

    if (!code) {
        return next();
    }

    directory(req)
        .send('GET', `/v11/invites/${encodeURIComponent(code)}/`)
        .then(res => {
            let { ok } = res;

            return res.json().then(body => ({ ok, body }));
        })
        .then(({ ok, body = {} }) => {
            req.ctx.invite = {
                ...body,
                code,
                valid: ok,
            };

            next();
        })
        .catch(() => {
            next();
        });
};
