import { useMutation } from '@tanstack/react-query';

import { useApiClient } from '@/lib/apiClient';
import { CHECKOUT_SOURCE, type CheckoutSource } from '@/lib/checkoutSource';
import { PlanKey } from '@/state/sessionStore';

interface SubscriptionCheckoutParams {
  planKey: PlanKey;
  period?: 'month' | 'year';
  clipId?: string;
  checkoutSource?: CheckoutSource;
}

export const useSubscriptionCheckout = () => {
  const apiClient = useApiClient();

  return useMutation({
    mutationFn: async ({
      planKey,
      period = 'month',
      clipId,
      checkoutSource = CHECKOUT_SOURCE.COMMERCIAL_RIGHTS_MODAL,
    }: SubscriptionCheckoutParams) => {
      const { data } = await apiClient.POST('/api/billing/create-session/', {
        body: {
          plan_key: planKey,
          period,
          clip_id: clipId,
          checkout_source: checkoutSource,
          currency: 'USD',
        },
      });

      return data;
    },
    onSuccess: (data) => {
      if (data?.url) {
        window.location.href = data.url;
      }
    },
    onError: (error) => {
      console.error('Subscription checkout failed:', error);
    },
  });
};
