import { validate } from "super-easy-validator"
import { ISocket, SocketEvent, SocketEventHandler } from "../../utils/types"
import { IUser } from "../users/models"
import services from "../../utils/services"
import { Chat } from "../chats/models"
import { IMessage } from "../messages/models"

const chatSockets = {} as Record<SocketEvent, SocketEventHandler>

chatSockets['messages-read'] = async (socket: ISocket, data: Record<string, any>) => {
  const user = socket.data.user as IUser
  const rule = { chat: 'mongoid' }
  const {errors} = validate(rule, data)
  if(errors) {
    return services.socketErrorNotifyUser(socket, 'validation-failed', {message: errors[0]})
  }
  const chat = await Chat.findById(data.chat).populate('lastMessage')
  if(!chat) {
    return services.socketErrorNotifyUser(socket, 'not-found', {message: 'chat not found'})
  }
  const currentParticipant = chat.participants.find(e => `${e.user}` === `${user._id}`)
  if(!currentParticipant) {
    return services.socketErrorNotifyUser(socket, 'permission-denied', {message: 'permission denied'})
  }

  currentParticipant.lastReadAt = new Date()
  await chat.save();

  for (const userId of chat.participants.map(e => `${e.user}`)) {
    const payload = {
      user: {
        _id: `${user._id}`,
        name: user.name,
        username: user.username,
        photo: user.photo,
      },
      chat: `${chat._id}`,
      lastReadAt: currentParticipant.lastReadAt.toISOString(),
      lastMessage: JSON.parse(JSON.stringify((chat.lastMessage as IMessage).toObject()))
    }
    services.socketNotifyUser({
      userId,
      event: 'messages-read',
      data: payload,
      currentSocket: socket.id,
      socketType: 'others'
    })
  }
}

export default chatSockets
