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

'use strict';

const express = require('express');
const passport = require('passport');

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

class HiveKaleidoscopeController extends SiteController {

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

    this.methods = [
      {
        name: 'postEvent',
        url: '/kaleidoscope/event',
        method: 'POST',
      },
    ];
  }

  async start ( ) {
    const router = express.Router();
    router.use(async (req, res, next) => {
      res.locals.currentView = 'hive';
      res.locals.hiveView = 'kaleidoscope';
      return next();
    });

    router.post(
      '/core/connect',
      this.postCoreNodeConnect.bind(this),
    );

    router.post(
      '/event',
      passport.authenticate('bearer', { session: false }),
      this.postEvent.bind(this),
    );

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

    return router;
  }

  async postCoreNodeConnect (req, res, next) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      switch (req.body.status) {
        case 'accepted':
          await coreNodeService.connect(req.body);
          return res.status(200).json({ success: true, message: 'Core OAuth2 credentials stored' });
        case 'rejected':
          await coreNodeService.rejectConnectRequest(req.body);
          return res.status(200).json({ success: true, message: 'Rejection acknowledged' });
        default:
          break;
      }
      res.status(500).json({
        success: false,
        message: "This node didn't understand the request",
      });
    } catch (error) {
      this.log.error('failed to create Core Node connection', { error });
      return next(error);
    }
  }

  async postEvent (req, res, next) {
    const { hive: hiveService } = this.dtp.services;
    try {
      this.log.debug('kaleidoscope event received', { event: req.body.event });
      const response = await hiveService.processKaleidoscopeEvent(req.body.event);
      res.status(200).json({ success: true, response });
    } catch (error) {
      this.log.error('failed to process Kaleidoscope event', { error });
      return next(error);
    }
  }

  async getKaleidoscopeRoot (req, res) {
    res.status(200).json({
      component: this.component,
      version: this.dtp.pkg.version,
      services: this.services,
      methods: this.methods,
    });
  }
}

module.exports = {
  name: 'hiveKaleidoscope',
  slug: 'hive-kaleidoscope',
  create: async (dtp) => { return new HiveKaleidoscopeController(dtp); },
};