// notification.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const express = require('express');

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

class NotificationController extends SiteController {

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

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

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

    router.use(async (req, res, next) => {
      res.locals.currentView = 'notification';
      return next();
    });

    router.param('notificationId', this.populateNotificationId.bind(this));

    router.get(
      '/:notificationId',
      limiterService.createMiddleware(limiterService.config.notification.getNotificationView),
      this.getNotificationView.bind(this),
    );

    router.get('/',
      limiterService.createMiddleware(limiterService.config.notification.getNotificationHome),
      this.getNotificationHome.bind(this),
    );
  }

  async populateNotificationId (req, res, next, notificationId) {
    const { userNotification: userNotificationService } = this.dtp.services;
    try {
      res.locals.notification = await userNotificationService.getById(notificationId);
      if (!res.locals.notification) {
        throw new SiteError(404, 'Notification not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate notificationId', { notificationId, error });
      return next(error);
    }
  }

  async getNotificationView (req, res) {
    res.render('notification/view');
  }

  async getNotificationHome (req, res, next) {
    const { userNotification: userNotificationService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.notifications = await userNotificationService.getForUser(req.user, res.locals.pagination);
      res.render('notification/index');
    } catch (error) {
      this.log.error('failed to render notification home view', { error });
      return next(error);
    }
  }
}

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