const Report = require('../core/report');

module.exports = app => {
    app.get(`/api/report/:name`, async(req, res, next) => {
        const args = req.query;
        const requiredArgs = ['clientId'];
        const argList = requiredArgs.join(',');
        const hasRequiredArgs = requiredArgs.every(arg => {
            return args[arg];
        });

        try {
            if (!hasRequiredArgs)
                throw new Error(`Required properties not found [${argList}]`);

            const report = new Report(req.params.name, args);
            const stream = await report.toPdfStream();
            res.setHeader('Content-type', 'application/pdf');
            stream.pipe(res);
        } catch (error) {
            next(error);
        }
    });
};