/**
 * WebSocketContext — global WebSocket provider.
 *
 * Wraps the app with a single WebSocket connection. On incoming events it
 * invalidates the relevant React Query caches so all subscribers refresh.
 */
import { createContext, useContext, useCallback } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useWebSocket, type WSEvent } from '../hooks/useWebSocket'

const WebSocketContext = createContext<null>(null)

export function WebSocketProvider({ children }: { children: React.ReactNode }) {
  const qc = useQueryClient()

  const onEvent = useCallback(
    (event: WSEvent) => {
      switch (event.type) {
        case 'render_complete':
        case 'render_failed':
          qc.invalidateQueries({ queryKey: ['orders'] })
          if (event.order_id) {
            qc.invalidateQueries({ queryKey: ['order', event.order_id as string] })
          }
          qc.invalidateQueries({ queryKey: ['worker-activity'] })
          break

        case 'cad_processing_complete':
          qc.invalidateQueries({ queryKey: ['worker-activity'] })
          break

        case 'order_status_change':
          qc.invalidateQueries({ queryKey: ['orders'] })
          if (event.order_id) {
            qc.invalidateQueries({ queryKey: ['order', event.order_id as string] })
          }
          break

        case 'queue_update':
          qc.setQueryData(['queue-status'], event.depths)
          break

        default:
          break
      }
    },
    [qc],
  )

  useWebSocket({ onEvent })

  return (
    <WebSocketContext.Provider value={null}>
      {children}
    </WebSocketContext.Provider>
  )
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function useWebSocketContext() {
  return useContext(WebSocketContext)
}
