"use client";

import useSWR from "swr";
import { fetcher, FetchError } from "@/lib/fetcher";

interface RoomSummary {
  id: string;
  code: string;
  name: string;
  creatorId: string;
  memberCount: number;
  poolCount: number;
  members: { id: string; username: string; avatar: string }[];
  lastDrawn: { content: string; createdAt: string } | null;
}

interface RoomsResponse {
  rooms: RoomSummary[];
}

export function useBlindboxRooms(userId: string | undefined) {
  const { data, error, isLoading, mutate } = useSWR<RoomsResponse>(
    userId ? `/api/blindbox/rooms?userId=${userId}` : null,
    fetcher,
    {
      revalidateOnFocus: true,
      revalidateOnReconnect: true,
      shouldRetryOnError: (err) =>
        !(err instanceof FetchError && (err.status === 401 || err.status === 403)),
    },
  );

  return {
    rooms: data?.rooms ?? [],
    isLoading,
    isUnauthorized: error instanceof FetchError && error.status === 401,
    error,
    mutate,
  };
}
