import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useRef } from 'react';

interface CheckoutSuccessDetection {
  isSuccess: boolean;
  checkoutSessionId: string | null;
  clearSuccess: () => void;
}

export const useCheckoutSuccessDetection = (): CheckoutSuccessDetection => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const processedSessionsRef = useRef<Set<string>>(new Set());

  const checkoutSessionId = searchParams.get(
    'commercial_rights_checkout_session_id'
  );
  const isSuccess =
    !!checkoutSessionId && !processedSessionsRef.current.has(checkoutSessionId);

  const clearSuccess = useCallback(() => {
    if (
      !checkoutSessionId ||
      processedSessionsRef.current.has(checkoutSessionId)
    )
      return;

    // Mark this session ID as processed
    processedSessionsRef.current.add(checkoutSessionId);

    // Remove the checkout session ID from URL immediately
    const newSearchParams = new URLSearchParams(searchParams.toString());
    newSearchParams.delete('commercial_rights_checkout_session_id');

    const newUrl =
      window.location.pathname +
      (newSearchParams.toString() ? `?${newSearchParams.toString()}` : '');
    router.replace(newUrl, { scroll: false });
  }, [checkoutSessionId, searchParams, router]);

  return {
    isSuccess,
    checkoutSessionId,
    clearSuccess,
  };
};
