/**
 * Socket.io API Endpoint for LocalGreenChain
 *
 * This endpoint initializes the Socket.io server and handles
 * the WebSocket upgrade for real-time communication.
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import type { Server as HTTPServer } from 'http';
import type { Socket as NetSocket } from 'net';
import { getSocketServer } from '../../lib/realtime/socketServer';

/**
 * Extended response type with socket server
 */
interface SocketResponse extends NextApiResponse {
  socket: NetSocket & {
    server: HTTPServer & {
      io?: ReturnType<typeof getSocketServer>['getIO'];
    };
  };
}

/**
 * Socket.io initialization handler
 *
 * This endpoint is called when the Socket.io client connects.
 * It initializes the Socket.io server if not already running.
 */
export default function handler(req: NextApiRequest, res: SocketResponse) {
  // Only allow GET requests for WebSocket upgrade
  if (req.method !== 'GET') {
    res.status(405).json({ error: 'Method not allowed' });
    return;
  }

  // Check if Socket.io is already initialized
  if (res.socket.server.io) {
    console.log('[Socket API] Socket.io already initialized');
    res.status(200).json({ status: 'ok', message: 'Socket.io already running' });
    return;
  }

  try {
    // Get the socket server singleton
    const socketServer = getSocketServer();

    // Initialize with the HTTP server
    socketServer.initialize(res.socket.server);

    // Store reference on the server object
    res.socket.server.io = socketServer.getIO();

    console.log('[Socket API] Socket.io initialized successfully');

    res.status(200).json({
      status: 'ok',
      message: 'Socket.io initialized',
      stats: socketServer.getStats(),
    });
  } catch (error) {
    console.error('[Socket API] Failed to initialize Socket.io:', error);
    res.status(500).json({
      status: 'error',
      message: 'Failed to initialize Socket.io',
      error: error instanceof Error ? error.message : 'Unknown error',
    });
  }
}

/**
 * Disable body parsing for WebSocket upgrade
 */
export const config = {
  api: {
    bodyParser: false,
  },
};
