import {
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import * as sessionsApi from "../../api/sessions";

const SESSIONS_KEY = ["sessions"] as const;

/**
 * List all live sessions. Polls on a short interval so consent-state
 * transitions (pending -> granted/denied) and viewer counts surface while the
 * page is open — a tech watching for an attended user to accept needs this to
 * move on its own. Slightly tighter than the machines poll because consent is a
 * time-sensitive, human-in-the-loop transition.
 */
export function useSessions() {
  return useQuery({
    queryKey: SESSIONS_KEY,
    queryFn: ({ signal }) => sessionsApi.listSessions(signal),
    refetchInterval: 8_000,
    staleTime: 4_000,
  });
}

/**
 * Mint a session-scoped viewer token. The server decides the access mode from
 * the caller's permissions; the result is shown in the join modal. No cache
 * invalidation — minting does not change session state.
 */
export function useMintViewerToken() {
  return useMutation({
    mutationFn: (sessionId: string) => sessionsApi.mintViewerToken(sessionId),
  });
}

/** End a session, then invalidate the list so it drops (or flips offline). */
export function useEndSession() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (sessionId: string) => sessionsApi.endSession(sessionId),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: SESSIONS_KEY });
    },
  });
}
