import constants from "../../utils/constants"
import services from "../../utils/services"
import { ScheduleEvent, SocketEventHandler } from "../../utils/types"
import { IUser, User } from "./models"

const userSchedules = {} as Record<ScheduleEvent, SocketEventHandler>

userSchedules['user-offline'] = async (data: Record<string, any>) => {
  // check if it has been 15 minutes or more for this user to be offline
  interface Payload {
    id: string
    user: string
  }
  const {user: userId} = data as Payload
  const user = await User.findById(userId)
  if(!user) {
    return
  }
  if(user.isManuallyOffline || user.isOnline || !user.lastOnlineAt) {
    return
  }
  const lastOnlineAt = new Date(user.lastOnlineAt)
  lastOnlineAt.setMinutes(lastOnlineAt.getMinutes() + constants.maxOnlineVisibilityInMinutes)
  if(lastOnlineAt > new Date()) {
    return
  }
  // notify all users that this user is offline
  await services.socketNotifyOnUserPresenceUpdated(user as IUser, 'offline')
}

export default userSchedules
