// email.js
// Copyright (C) 2021 Digital Telepresence, LLC
// License: Apache-2.0

'use strict';

const express = require('express');

const { SiteController/*, SiteError*/ } = require('../../lib/site-lib');

class EmailController extends SiteController {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  async start ( ) {
    const { jobQueue: jobQueueService, limiter: limiterService } = this.dtp.services;

    this.emailJobQueue = jobQueueService.getJobQueue('email', this.dtp.config.jobQueues.email);

    const router = express.Router();
    this.dtp.app.use('/email', router);

    router.get(
      '/verify',
      limiterService.createMiddleware(limiterService.config.email.getEmailVerify),
      this.getEmailVerify.bind(this),
    );

    router.get(
      '/opt-out',
      limiterService.createMiddleware(limiterService.config.email.getEmailOptOut),
      this.getEmailOptOut.bind(this),
    );

    return router;
  }

  async getEmailOptOut (req, res, next) {
    const { user: userService } = this.dtp.services;
    try {
      await userService.emailOptOut(req.query.u, req.query.c);
      res.render('email/opt-out-success');
    } catch (error) {
      this.log.error('failed to opt-out from email', {
        userId: req.query.t,
        category: req.query.c,
        error,
      });
      return next(error);
    }
  }

  async getEmailVerify (req, res, next) {
    const { email: emailService } = this.dtp.services;
    try {
      await emailService.verifyToken(req.query.t);
      res.render('email/verify-success');
    } catch (error) {
      this.log.error('failed to verify email', { error });
      return next(error);
    }
  }
}

module.exports = {
  slug: 'email',
  name: 'email',
  create: async (dtp) => { return new EmailController(dtp); },
};