/// / develop environment config
const { isDev, isProduction, DevServerPort } = require('./_env')
const wss = require('./WebSocket/wss')
/// / init express app (wrapping all functions into init() to prevent running in development mode by nuxt dev mode)
function init() {
  // run preConfigured modules
  require('./database')
  require('body-parser')

  // include modules to configure
  const express = require('express')
  const fileUpload = require('express-fileupload')
  const authentication = require('./authentication')
  const { checkThirdPartyAccess } = require('./plugins/checkThirdPartyAccess')
  const { rs } = require('./plugins/resHeader')
  // const { getVerityToken, getPanatechToken } = require('./ArpaWebService')
  const cronJobs = require('./plugins/cronJobs')
  const router = express.Router()

  // Create express instance
  const app = express()

  // Init body-parser options (inbuilt with express)
  app.use(express.json())
  app.use(express.urlencoded({ extended: true }))
  app.use(fileUpload())
  app.use(rs)
  console.log('🟢 ~ Node Server is running ')
  // load plugins
  // getVerityToken()
  // getPanatechToken()
  cronJobs()

  // API routes
  const Public = require('./routes/public')
  const admin = require('./routes/admin')
  const user = require('./routes/user')
  const agent = require('./routes/agent')
  const auth = require('./routes/auth')
  const cross = require('./routes/cross')
  const thirdParty = require('./routes/thirdParty')

  // Use API Routes
  router.use('/public', Public)
  router.use('/admin', authentication.isAdmin, admin)
  router.use('/user', authentication.isUser, user)
  router.use('/agent', authentication.isAgent, agent)
  router.use('/auth', auth)
  router.use('/cross', cross)
  router.use('/thirdParty', checkThirdPartyAccess, thirdParty)

  app.use(isDev ? '/api' : '', router)


  return app
}

/// / development server
if (isDev) {
  init().listen(DevServerPort, () => {
    console.log('🟢 ~ Node Server is running in development mode on port:', DevServerPort)
  })
  wss()
}

/// / server middleware (production mode)
module.exports.serverMiddleware = isProduction && { path: '/api', handler: init() }
