"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';
import {
  createCheckoutSession,
  createPortalSession,
} from '@/lib/api/subscription';
import type {
  CheckoutSessionRequest,
  PortalSessionRequest,
} from '@/lib/api/subscription';

export function useSubscriptionStatus() {
  const { subscription } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('subscription', 'status'),
    queryFn: () => subscription.getStatus(),
  });
}

export function useFeatureBenefits() {
  const { subscription } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('subscription', 'features'),
    queryFn: () => subscription.getFeatureBenefits(),
    staleTime: Infinity,
  });
}

export function useUpgradeTriggers() {
  const { subscription } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('subscription', 'upgrade-triggers'),
    queryFn: () => subscription.getUpgradeTriggers(),
    staleTime: Infinity,
  });
}

// ---------------------------------------------------------------------------
// Mutation hooks (Stripe Checkout / Portal)
// ---------------------------------------------------------------------------

export function useCreateCheckoutSession() {
  const queryClient = useQueryClient();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: CheckoutSessionRequest) => createCheckoutSession(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('subscription') });
    },
  });
}

export function useCreatePortalSession() {
  const queryClient = useQueryClient();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: PortalSessionRequest) => createPortalSession(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('subscription') });
    },
  });
}
