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

'use strict';

const express = require('express');

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

class SettingsController extends SiteController {

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

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

    router.post('/', this.postUpdateSettings.bind(this));

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

    return router;
  }

  async postUpdateSettings (req, res, next) {
    const { cache: cacheService } = this.dtp.services;
    try {
      const settingsKey = `settings:${this.dtp.config.site.domainKey}:site`;
      await cacheService.setObject(settingsKey, req.body);
      res.redirect('/admin/settings');
    } catch (error) {
      return next(error);
    }
  }

  async getSettingsView (req, res, next) {
    try {
      res.render('admin/settings/editor');
    } catch (error) {
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminSettings',
  slug: 'admin-settings',
  create: async (dtp) => { return new SettingsController(dtp); },
};