import type { Server as SocketServer } from 'socket.io'
import type { ChatClientMessage, ChatMessage } from '../types/chat.ts'
import { v4 as uuidv4 } from 'uuid'

export default async function (io: SocketServer) {
  const messages: ChatMessage[] = []

  io.on('connection', async (socket) => {
    socket.on('chat:message', async (clientMessage: ChatClientMessage, cb) => {
      const message: ChatMessage = {
        id: uuidv4(),
        createdAt: new Date().toISOString(),
        sender: socket.data.username,
        text: clientMessage.text,
      }

      console.log(message)

      messages.push(message)

      if (messages.length > 5000) {
        messages.shift()
      }

      io.emit('chat:new-message', message)
    })
  })
}
