import { createServer as createHttpServer } from 'node:http'
import { consola } from 'consola'
import cors from 'cors'
import express from 'express'
import * as mediasoup from 'mediasoup'
import { Server as SocketServer } from 'socket.io'
import { webrtcSocket } from './sockets'

(async () => {
  const app = express()

  app.use(cors())

  const server = createHttpServer(app)

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

    process.exit(1)
  })

  const router = await worker.createRouter({
    mediaCodecs: [
      {
        kind: 'audio',
        mimeType: 'audio/opus',
        clockRate: 48000,
        channels: 2,
        parameters: { useinbandfec: 1, stereo: 1 },
      },
    ],
  })

  const io = new SocketServer(server, {
    path: '/chad/ws',
    cors: {
      origin: process.env.CORS_ORIGIN || '*',
    },
  })

  webrtcSocket(io, router)

  server.listen(process.env.PORT || 4000, () => {
    consola.success('[Server]', 'Server started!')
  })
})()
