/**
 * WebSocket server for GraphQL subscriptions
 */

import { WebSocketServer } from 'ws'
import { useServer } from 'graphql-ws/lib/use/ws'
import { schema } from '../schema'
import { createContext } from '../context'
import { FastifyRequest } from 'fastify'

export function createWebSocketServer(httpServer: any, path: string) {
  const wss = new WebSocketServer({
    server: httpServer,
    path,
  })

  const serverCleanup = useServer(
    {
      schema,
      context: async (ctx) => {
        // Create a mock request for context
        const request = {
          headers: ctx.connectionParams?.authorization
            ? { authorization: ctx.connectionParams.authorization as string }
            : {},
        } as FastifyRequest

        return createContext(request)
      },
      onConnect: async (ctx) => {
        // Validate connection - check authentication if needed
        // For now, allow all connections
        return true
      },
      onDisconnect: (ctx, code, reason) => {
        // Handle disconnection
        logger.info('WebSocket client disconnected', { code, reason })
      },
      onError: (ctx, msg, errors) => {
        logger.error('WebSocket error', { message: msg, errors })
      },
    },
    wss
  )

  // Graceful shutdown
  const shutdown = () => {
    serverCleanup.dispose()
    wss.close()
  }

  process.on('SIGTERM', shutdown)
  process.on('SIGINT', shutdown)

  return {
    wss,
    serverCleanup,
    shutdown,
  }
}

