import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { subscriptionService } from "./service";
import type { CreateCheckoutRequest, CancelSubscriptionRequest } from "./types";

export const SubscriptionQueryKeys = {
  all: ["subscriptions"] as const,
  plans: () => [...SubscriptionQueryKeys.all, "plans"] as const,
  me: () => [...SubscriptionQueryKeys.all, "me"] as const,
};

/**
 * Fetch all available plans (public, no auth required)
 */
export const useSubscriptionPlans = () => {
  return useQuery({
    queryKey: SubscriptionQueryKeys.plans(),
    queryFn: () => subscriptionService.getPlans(),
    staleTime: 1000 * 60 * 30, // Plans rarely change — 30 min cache
  });
};

/**
 * Fetch current user subscription status
 */
export const useMySubscription = (enabled = true) => {
  return useQuery({
    queryKey: SubscriptionQueryKeys.me(),
    queryFn: () => subscriptionService.getMySubscription(),
    enabled,
  });
};

/**
 * Get Paddle checkout config for a plan
 */
export const useCheckoutConfig = () => {
  return useMutation({
    mutationFn: (dto: CreateCheckoutRequest) =>
      subscriptionService.getCheckoutConfig(dto),
  });
};

/**
 * Cancel the current subscription
 */
export const useCancelSubscription = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (dto: CancelSubscriptionRequest) =>
      subscriptionService.cancelSubscription(dto),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: SubscriptionQueryKeys.me(),
      });
    },
  });
};
