import {
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import * as codesApi from "../../api/codes";
import type { CreateCodeRequest } from "../../api/types";

const CODES_KEY = ["codes"] as const;

/**
 * List the active support codes. Polls on a short interval because codes are
 * short-lived: a `pending` code can be redeemed (-> `connected`) or expire out
 * of the active set at any moment, and a tech who just read a code aloud is
 * watching for exactly that transition. The interval is tight (like the
 * sessions poll) so the redeem shows up on its own without a manual refresh.
 */
export function useSupportCodes() {
  return useQuery({
    queryKey: CODES_KEY,
    queryFn: ({ signal }) => codesApi.listCodes(signal),
    refetchInterval: 7_000,
    staleTime: 3_500,
  });
}

/**
 * Generate a new support code, then invalidate the list so the new `pending`
 * code appears in the table. The created code is returned to the caller so the
 * generate flow can surface it prominently (it is read to the end user).
 */
export function useGenerateCode() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: CreateCodeRequest) => codesApi.createCode(body),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: CODES_KEY });
    },
  });
}

/**
 * Cancel (revoke) a support code, then invalidate the list so the row drops out
 * of the active set. Cancelling an un-redeemed code is irreversible, so the UI
 * confirms first; this hook is the action behind that confirmation.
 */
export function useCancelCode() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (code: string) => codesApi.cancelCode(code),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: CODES_KEY });
    },
  });
}
