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

'use strict';

const express = require('express');

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

class ContentReportController extends SiteController {

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

  async start ( ) {
    const upload = this.createMulter();

    const router = express.Router();
    router.use(async (req, res, next) => {
      res.locals.currentView = 'admin';
      res.locals.adminView = 'content-report';
      return next();
    });

    router.param('reportId', this.populateReportId.bind(this));

    router.post('/:reportId/action', upload.none(), this.postReportAction.bind(this));

    router.get('/:reportId', this.getReportView.bind(this));

    router.get('/', this.getIndex.bind(this));

    return router;
  }

  async populateReportId (req, res, next, reportId) {
    const { contentReport: contentReportService } = this.dtp.services;
    try {
      res.locals.report = await contentReportService.getById(reportId);
      return next();
    } catch (error) {
      this.log.error('failed to populate content report', { reportId, error });
      return next(error);
    }
  }

  async postReportAction (req, res, next) {
    const { contentReport: contentReportService } = this.dtp.services;
    try {
      this.log.info('postReportAction', { body: req.body });
      switch (req.body.verb) {
        case 'remove':
          await contentReportService.removeResource(res.locals.report);
          break;
        
        case 'dismiss':
          await contentReportService.setStatus(res.locals.report, 'ignored');
          break;
      }

      const displayList = this.createDisplayList('add-recipient');
      displayList.navigateTo('/admin/content-report');
      res.status(200).json({ success: true, displayList });
    } catch (error) {
      this.log.error('failed to perform content report action', { verb: req.body.verb, error });
      return next(error);
    }
  }

  async getReportView (req, res) {
    res.render('admin/content-report/view');
  }

  async getIndex (req, res, next) {
    const { contentReport: contentReportService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.reports = await contentReportService.getReports(['new'], res.locals.pagination);
      res.render('admin/content-report/index');
    } catch (error) {
      this.log.error('failed to display content report index', { error });
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminContentReport',
  slug: 'admin-content-report',
  create: async (dtp) => { return new ContentReportController(dtp); },
};