// src/server/features/system/index.ts
// System feature plugin - registers system management routes

import fp from 'fastify-plugin';
import { FastifyPluginAsync } from 'fastify';
import { systemRoutes } from './system.routes';
import { onEvent } from '@serverShared/lib/events';
import { logger } from '@serverShared/lib/logger';

export const systemPlugin: FastifyPluginAsync = fp(async (fastify) => {
  onEvent<{ roles: string[] }>('system:permissions_updated', async (data) => {
    if (!fastify.hasDecorator('io') || !fastify.io) {
      logger.warn('[System] Socket.io decorator is unavailable, skip broadcasting system:permissions_updated');
      return;
    }

    fastify.io.emit('system:permissions_updated', data);
  });

  onEvent('session:policy_updated' as any, async () => {
    if (!fastify.hasDecorator('io') || !fastify.io) {
      logger.warn('[System] Socket.io decorator is unavailable, skip broadcasting session:policy_updated');
      return;
    }

    (fastify.io as any).emit('session:policy_updated', {});
  });

  await fastify.register(systemRoutes, { prefix: '/api/system' });
}, { name: 'system' });

export default systemPlugin;
