"use client"

import useSWR from "swr"
import * as api from "./api"

export function useRooms() {
  const { data, error, isLoading, mutate } = useSWR("rooms", () => api.getRooms())
  return { rooms: data ?? [], error, isLoading, mutate }
}

// activeRoomId === null => all rooms combined via /events
export function useEvents(activeRoomId: number | null, from?: string, to?: string) {
  const key = activeRoomId === null ? ["events", from, to] : ["room-events", activeRoomId, from, to]
  const { data, error, isLoading, mutate } = useSWR(key, () =>
    activeRoomId === null
      ? api.getUserEvents(from, to)
      : api.getRoomEvents(activeRoomId, from, to),
  )
  return { events: data ?? [], error, isLoading, mutate }
}

export function useRoomMembers(roomId: number | null) {
  const { data, error, isLoading, mutate } = useSWR(
    roomId === null ? null : ["room-members", roomId],
    () => api.getRoomMembers(roomId as number),
  )
  return { members: data ?? [], error, isLoading, mutate }
}

export function useRoomPermissions(roomId: number | null) {
  const { data, error, isLoading, mutate } = useSWR(
    roomId === null ? null : ["room-whoami", roomId],
    () => api.roomWhoami(roomId as number),
  )
  return { permissions: data, error, isLoading, mutate }
}
