import { consola } from 'consola'
import fp from 'fastify-plugin'
import * as mediasoup from 'mediasoup'

declare module 'fastify' {
  interface FastifyInstance {
    mediasoupWorker: mediasoup.types.Worker
  }
}

export default fp(
  async (fastify) => {
    const worker = await mediasoup.createWorker()
    worker.on('died', () => {
      consola.error('[Mediasoup]', 'Worker died, exiting...')

      process.exit(1)
    })

    fastify.decorate('mediasoupWorker', worker)
  },
  { name: 'mediasoup-worker' },
)
