import { useEffect } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { Clip } from '@/state/clipStore';
import { MenusStore } from '@/state/menusStore';
import { downloadClipAudio } from '@/utils/download';

import { useCheckoutSuccessDetection } from './useCheckoutSuccessDetection';

interface UseCommercialRightsSuccessHandlerProps {
  clip: Clip;
  menus: MenusStore;
}

/**
 * Hook that handles commercial rights checkout success detection
 * and automatically opens the rights purchased modal with download functionality.
 * Eliminates code duplication between Desktop and Mobile song pages.
 */
export const useCommercialRightsSuccessHandler = ({
  clip,
  menus,
}: UseCommercialRightsSuccessHandlerProps) => {
  const { session } = useStores();
  const {
    isSuccess: isCheckoutSuccess,
    checkoutSessionId,
    clearSuccess,
  } = useCheckoutSuccessDetection();

  useEffect(() => {
    if (isCheckoutSuccess && checkoutSessionId) {
      menus.openCommercialRightsModal(clip.id, async () => {
        try {
          await downloadClipAudio(menus.apiClient, clip, session);
        } catch (error) {
          console.warn('Failed to download after rights purchase:', error);
        }
      });

      clearSuccess();
    }
  }, [isCheckoutSuccess, checkoutSessionId, clip, menus, clearSuccess]);
};
