import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";

import { useAuth } from "@/hooks/useAuth";
import { getMyPlan } from "@/lib/plan.functions";

/**
 * Client-side view of the signed-in user's plan.
 * Anonymous visitors resolve to the free tier, so premium courses stay locked.
 */
export function usePlan() {
  const { session, loading } = useAuth();
  const fetchPlan = useServerFn(getMyPlan);

  const query = useQuery({
    queryKey: ["my-plan", session?.user.id ?? "anon"],
    queryFn: () => fetchPlan(),
    enabled: Boolean(session),
    staleTime: 30_000,
  });

  return {
    plan: query.data ?? null,
    isPro: Boolean(query.data?.isPro),
    signedIn: Boolean(session),
    loading: loading || (Boolean(session) && query.isLoading),
  };
}
