text: const { Router } = require('express')
  
  const { authenticate } = require('../../middlewares')
  const { sendSignalSchema } = require('./signal.schemas')
  const SignalError = require('./signal.model')
  const validate = require('../../utils/joi-validate-wrapper')
  const sendSignal = require('./lib/send-signal')
  const initDiscord = require('../../discord')
  const createErrorMessage = require('./lib/create-error-message')
  
  const dmChannel = initDiscord()
  
  const router = new Router()
  
  const saveAndCreateMessages = async (errors, strategy, type) => {
    const errorEmbeds = []
    let errorMessage = `SendSignalError: Could not send ${type} signal to `
  
    for (let i = 0; i < errors.length; i += 1) {
      const { signalProvider, data } = errors[i]
  
      const signalError = new SignalError({
        signalProvider,
        strategy,
        action: type,
        status: data.status,
        statusText: data.statusText,
      })
  
      // eslint-disable-next-line no-await-in-loop
      await signalError.save()
  
      errorEmbeds.push(createErrorMessage(signalProvider, type, data.status, data.statusText, strategy))
      errorMessage += `${signalProvider},`
    }
  
    return {
      errorEmbeds,
      errorMessage: errorMessage.slice(0, -1),
    }
  }
  
  router.post('/:action', authenticate, async (req, res, next) => {
    try {
      const { params, body } = req
  
      const validatedBody = await validate(sendSignalSchema, body)
  
      const {
        strategy, baseAsset, quoteAsset, side, positionId, futures, signalProviders,
      } = validatedBody
  
      if (params.action === 'open') {
        const errors = await sendSignal(signalProviders, strategy, {
          baseAsset,
          quoteAsset,
          side,
          positionId,
          futures,
        }, 'entry')
  
        if (errors.filter((error) => !!error).length) {
          const { errorEmbeds, errorMessage } = await saveAndCreateMessages(errors, strategy, params.action)
          dmChannel.send({ embeds: errorEmbeds })
  
          throw {
            status: 502,
            name: 'ProviderError',
            messages: [errorMessage],
          }
        }
  
        res.status(200).json({
          success: true,
          data: {
            message: `Successfully opened position on ${signalProviders.join(', ')}`,
          },
        })
        return
      }
  
      if (params.action === 'close') {
        const errors = await sendSignal(signalProviders, strategy, {
          baseAsset,
          quoteAsset,
          positionId,
          side,
          futures,
        }, 'exit')
  
        if (errors.filter((error) => !!error).length) {
          const { errorEmbeds, errorMessage } = await saveAndCreateMessages(errors, strategy, params.action)
          dmChannel.send({ embeds: errorEmbeds })
  
          throw {
            status: 502,
            name: 'ProviderError',
            messages: [errorMessage],
          }
        }
  
        res.status(200).json({
          success: true,
          data: {
            message: `Successfully closed position on ${signalProviders.join(', ')}`,
          },
        })
      }
    } catch (error) {
      console.log(error)
      next(error)
    }
  })
  
  module.exports = router
  