import { io, Socket } from 'socket.io-client'

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  let socket: Socket | null = null

  const connect = (token: string) => {
    if (socket?.connected) return socket

    socket = io(config.public.wsUrl as string, {
      auth: { token },
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5
    })

    socket.on('connect', () => {
      console.log('WebSocket connected')
    })

    socket.on('disconnect', () => {
      console.log('WebSocket disconnected')
    })

    socket.on('connect_error', (error) => {
      console.error('WebSocket connection error:', error)
    })

    return socket
  }

  const disconnect = () => {
    socket?.disconnect()
    socket = null
  }

  return {
    provide: {
      socket: {
        connect,
        disconnect,
        get instance() {
          return socket
        }
      }
    }
  }
})
