const app = require('../../server/server');
const loopback = require('loopback');
const path = require('path');

function getUrl() {
  return app.get('rootUrl') || app.get('url');
}

function getFrom() {
  return app.dataSources.email.settings.transports[0].auth.from;
}

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
    this.statusCode = 422;
  }
}

module.exports = function (Self) {
  Self.afterRemote('create', async function(ctx, instance) {
    const url = new URL(getUrl());
    const options = {
      type: 'email',
      to: instance.email,
      from: getFrom(),
      subject: 'Thanks for registering',
      template: path.resolve(__dirname, '../../views/verify.ejs'),
      redirect: `${getUrl()}#/login/${instance.email}?emailConfirmed`,
      host: url.hostname,
      port: url.port,
      protocol: url.protocol.split(':')[0],
      user: Self
    };
    instance.verify(options)
      .then(res => console.log('> Verification email sent:', res));
  });

  Self.validatePassword = function(password) {
    if (!password) {
      throw new ValidationError('passwordEmpty');
    }

    const pattern = new RegExp('(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.{6,})')
    if (!pattern.test(password)) {
      throw new ValidationError('passwordRequeriments');
    }
  };

  Self.on('resetPasswordRequest', async function(info) {
    const renderer = loopback.template(path.resolve(__dirname, '../../views/reset-password.ejs'));
    const html = renderer({
      url: `${getUrl()}#/reset-password?access_token=${info.accessToken.id}`
    });

    await app.models.Email.send({
      to: info.email,
      from: getFrom(),
      subject: 'Password reset',
      html
    });
    console.log('> Sending password reset email to:', info.email);
  });
};
