// src/server/features/blacklist/lib/blacklist.events.ts
// Event listeners and emitters for blacklist module

import { emitter, onEvent } from '../../../shared/lib/events';
import { logger } from '../../../shared/lib/logger';
import type { BlacklistEntry } from '@shared/contracts/blacklist';
import type { FastifyInstance } from 'fastify';

// Store fastify instance for Socket.io access
let fastifyInstance: FastifyInstance | null = null;

/**
 * Initialize blacklist event listeners with fastify instance
 * Call this once during application initialization
 */
export function registerBlacklistEventListeners(fastify?: FastifyInstance): void {
  // Store fastify instance for Socket.io access
  if (fastify) {
    fastifyInstance = fastify;
  }

  // Listen for blacklist:created events
  onEvent<BlacklistEntry>('blacklist:created', async (data) => {
    try {
      logger.info(`[Events] blacklist:created received for entry ${data.id}`);
      
      // Broadcast to all connected clients via Socket.io
      if (fastifyInstance && fastifyInstance.io) {
        fastifyInstance.io.emit('blacklist:created', data);
      }
    } catch (error) {
      logger.error(`[Events] Error handling blacklist:created:`, error);
    }
  });

  // Listen for blacklist:updated events
  onEvent<BlacklistEntry | { action: 'fullRefresh'; count: number }>('blacklist:updated', async (data) => {
    try {
      logger.info(`[Events] blacklist:updated received for entry ${'id' in data ? data.id : 'fullRefresh'}`);
      
      // Broadcast to all connected clients via Socket.io
      if (fastifyInstance && fastifyInstance.io) {
        fastifyInstance.io.emit('blacklist:updated', data);
      }
    } catch (error) {
      logger.error(`[Events] Error handling blacklist:updated:`, error);
    }
  });

  // Listen for blacklist:deleted events
  onEvent<{ id: string }>('blacklist:deleted', async (data) => {
    try {
      logger.info(`[Events] blacklist:deleted received for entry ${data.id}`);
      
      // Broadcast to all connected clients via Socket.io
      if (fastifyInstance && fastifyInstance.io) {
        fastifyInstance.io.emit('blacklist:deleted', data);
      }
    } catch (error) {
      logger.error(`[Events] Error handling blacklist:deleted:`, error);
    }
  });

  logger.info('[Events] Blacklist event listeners registered successfully');
}

/**
 * Helper function to emit blacklist:created event
 */
export async function emitBlacklistCreatedEvent(data: BlacklistEntry): Promise<void> {
  await emitter.emit('blacklist:created', data);
}

/**
 * Helper function to emit blacklist:updated event
 */
export async function emitBlacklistUpdatedEvent(data: BlacklistEntry): Promise<void> {
  await emitter.emit('blacklist:updated', data);
}

/**
 * Helper function to emit blacklist:deleted event
 */
export async function emitBlacklistDeletedEvent(data: { id: string }): Promise<void> {
  await emitter.emit('blacklist:deleted', data);
}
