/**
 * Socket.io Stats API Endpoint
 *
 * Returns statistics about the WebSocket server and connections.
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getSocketServer } from '../../../lib/realtime/socketServer';
import { getEventStream } from '../../../lib/transparency/EventStream';

interface SocketStats {
  server: {
    connectedClients: number;
    rooms: string[];
    uptime: number;
  };
  events: {
    totalEvents: number;
    eventsLast24h: number;
    eventsByType: Record<string, number>;
    averageEventsPerMinute: number;
  };
  status: 'running' | 'stopped';
}

/**
 * Get Socket.io server statistics
 */
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<SocketStats | { error: string }>
) {
  if (req.method !== 'GET') {
    res.status(405).json({ error: 'Method not allowed' });
    return;
  }

  try {
    const socketServer = getSocketServer();
    const eventStream = getEventStream();

    const serverStats = socketServer.getStats();
    const eventStats = eventStream.getStats();

    const stats: SocketStats = {
      server: serverStats,
      events: {
        totalEvents: eventStats.totalEvents,
        eventsLast24h: eventStats.eventsLast24h,
        eventsByType: eventStats.eventsByType,
        averageEventsPerMinute: eventStats.averageEventsPerMinute,
      },
      status: socketServer.getIO() ? 'running' : 'stopped',
    };

    res.status(200).json(stats);
  } catch (error) {
    console.error('[Socket Stats API] Error:', error);
    res.status(500).json({
      error: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}
