import fp from 'fastify-plugin';
import type { FastifyInstance } from 'fastify';
import { Server } from 'socket.io';

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

export default fp(async function socketPlugin(fastify: FastifyInstance) {
  const io = new Server(fastify.server, {
    cors: {
      origin: fastify.config.NODE_ENV === 'development'
        ? '*'
        : process.env['ALLOWED_ORIGINS']?.split(',') ?? [],
      credentials: true,
    },
  });

  io.on('connection', (socket) => {
    socket.on('join-tenant', (tenantId: string) => {
      socket.join(`tenant:${tenantId}`);
    });

    socket.on('leave-tenant', (tenantId: string) => {
      socket.leave(`tenant:${tenantId}`);
    });
  });

  fastify.decorate('io', io);

  fastify.addHook('onClose', async () => {
    await new Promise<void>((resolve) => io.close(() => resolve()));
  });
});
