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) {
    const statusCode = error.code || error.status;

    if ([400, 401, 403, 404, 409, 422].includes(statusCode)) {
      return res.status(statusCode).send(error.message);
    }

    console.error(error);
    return res.status(500).send('Internal server error');
  }

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

  static isUuidV4(value) {
    return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
      value,
    );
  }
};
