const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const config = require('./config');
const { captureError } = require('./security/monitoring');

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 (res.headersSent) {
      return next(error);
    }

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

    console.error(error);
    captureError(error, req.requestId);
    return res.status(500).send({ error: 'internal_server_error', request_id: req.requestId });
  }

  static jwtSign(data) {
    return jwt.sign(data, config.secret_key, {
      expiresIn: '30m',
      jwtid: crypto.randomUUID(),
    });
  }
};
