const express = require('express');
const config = require('../../config/default');
const logger = require('../utils/logger');

function createHttpJsonConnector() {
  let server;
  let messageHandler = async () => {};
  let errorHandler = (err) => logger.error({ err }, 'connector error');

  const app = express();
  app.use(express.json());
  app.post('/messages', async (req, res) => {
    try {
      await messageHandler(req.body);
      res.status(202).json({ status: 'queued' });
    } catch (err) {
      errorHandler(err);
      res.status(500).json({ status: 'error', message: err.message });
    }
  });

  return {
    name: () => 'http-json',
    type: () => 'http-json',
    async start() {
      return new Promise((resolve) => {
        server = app.listen(config.connectors.httpJsonPort, () => {
          logger.info({ port: config.connectors.httpJsonPort }, 'http-json connector listening');
          resolve();
        });
      });
    },
    async stop() {
      if (!server) return;
      return new Promise((resolve, reject) => {
        server.close((err) => {
          if (err) return reject(err);
          resolve();
        });
      });
    },
    health() {
      return { status: server ? 'up' : 'down', port: config.connectors.httpJsonPort };
    },
    onMessage(handler) {
      messageHandler = handler;
    },
    onError(handler) {
      errorHandler = handler;
    }
  };
}

module.exports = { createHttpJsonConnector };
