import type { ChadClient, UpdatedClient } from '#shared/types'
import { createGlobalState } from '@vueuse/core'

export const useClients = createGlobalState(() => {
  const signaling = useSignaling()
  const toast = useToast()

  const clients = shallowRef<ChadClient[]>([])

  watch(signaling.socket, (socket) => {
    if (!socket)
      return

    socket.on('clientChanged', (clientId: ChadClient['id'], updatedClient: UpdatedClient) => {
      const client = getClient(clientId)
      updateClient(clientId, updatedClient)

      if (updatedClient.username)
        toast.add({ severity: 'info', summary: `${client?.username} is now ${updatedClient.username}`, closable: false, life: 1000 })
    })
  })

  function getClient(clientId: ChadClient['id']) {
    return clients.value.find(client => client.id === clientId)
  }

  function addClient(...client: ChadClient[]) {
    clients.value.push(...client)

    triggerRef(clients)
  }

  function removeClient(clientId: ChadClient['id']) {
    clients.value = clients.value.filter(client => client.id !== clientId)
  }

  function updateClient(clientId: ChadClient['id'], updatedClient: UpdatedClient) {
    const clientIdx = clients.value.findIndex(client => client.id === clientId)

    if (clientIdx === -1)
      return

    clients.value[clientIdx] = {
      ...clients.value[clientIdx],
      ...updatedClient,
    } as ChadClient

    triggerRef(clients)
  }

  return {
    clients,
    getClient,
    addClient,
    removeClient,
    updateClient,
  }
})
