const mailSend = require('../util/mailSend');
const sys = require('../config/sys');

let api, adminMail;

class OwnError extends Error {
  constructor(msg = '', code = 400, additional = undefined) {
    super();
    this.msg = msg;
    this.code = code;
    this.additional = additional;
  }
}

function err(msg, code, additional) {
  throw (new OwnError(msg, code, additional));
}

async function error(ctx, next) {
  try {
    ctx[api] = err;
    await next()
  } catch (e) {
    let body;

    if (e instanceof OwnError) {
      ctx.status = e.code
      body = {
        msg: e.msg,
        content: e.additional
      }
    } else {
      ctx.status = 500
      body = {code: 500, msg: '系统发生错误，请稍后再试！'};

      if (!sys.debug && adminMail) {
        await mailSend({
            to: adminMail,
            subject: '4维时代错误提醒',
            html: `<h1>${e.message}</h1><div>${e.stack ? e.stack.replace(/\n/ig, '<br>') : e}</div>`
        });
      } else {
        throw e;
      }
    }

    ctx.body = body;
  }
}


function init(_api = 'error', _adminMail) {
  api = _api;
  adminMail = _adminMail;

  return error;
}

module.exports = exports = init;