const jwt = require('jsonwebtoken');
const config = require('./config');

module.exports = class Helpers {
  static wrapAsync(fn) {
    return function (req, res, next) {
      fn(req, res, next).catch(next);
    };
  }

  static commonErrorHandler(error, req, res, next) {
    if ([400, 403, 404].includes(error.code)) {
      return res.status(error.code).send(error.message);
    }

    console.error(error);
    return res.status(500).send(error.message);
  }

  static jwtSign(data) {
    return jwt.sign(data, config.secret_key, {expiresIn: '6h'});
  };

  static async exportData(res, type, entityName, fields, rows) {
    if (type === 'csv') {
      const { parse } = require('json2csv');
      const csv = parse(rows, { fields });
      res.header('Content-Type', 'text/csv');
      res.attachment(`${entityName}.csv`);
      return res.send(csv);
    } else if (type === 'xlsx') {
      const ExcelJS = require('exceljs');
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet(entityName);

      worksheet.columns = fields.map(field => ({ header: field, key: field }));
      worksheet.addRows(rows);

      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename=${entityName}.xlsx`);

      await workbook.xlsx.write(res);
      return res.end();
    }
  }
};
