"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(enabled: boolean) {
  const { data, error, isLoading, mutate } = useSWR<RoomsResponse>(
    enabled ? "/api/blindbox/rooms" : 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,
  };
}
