import type { FastifyInstance } from 'fastify'
import type { ServerOptions } from 'socket.io'
import fp from 'fastify-plugin'
import { Server } from 'socket.io'
import registerChatSocket from '../socket/chat.ts'
import registerWebrtcSocket from '../socket/webrtc.ts'

declare module 'fastify' {
  interface FastifyInstance {
    io: Server
  }
}

export default fp<Partial<ServerOptions>>(
  async (fastify, opts) => {
    fastify.decorate('io', new Server(fastify.server, opts))

    fastify.addHook('preClose', () => {
      fastify.io.disconnectSockets(true)
    })

    fastify.addHook('onClose', async (fastify: FastifyInstance) => {
      await fastify.io.close()
    })

    fastify.ready(async () => {
      await registerWebrtcSocket(fastify.io, fastify.mediasoupRouter)
      await registerChatSocket(fastify.io)
    })
  },
  { name: 'socket-io', dependencies: ['mediasoup-worker', 'mediasoup-router'] },
)

export const autoConfig: Partial<ServerOptions> = {
  path: '/chad/ws',
  cors: {
    origin: process.env.CORS_ORIGIN || '*',
    methods: ['GET', 'POST'],
    credentials: true,
  },
}
