import { useCallback } from 'react';
import { usePersSDK } from '../providers/PersSDKProvider';
import type { PurchaseTokenDTO, PurchaseDTO, PaginatedResponseDTO } from '@explorins/pers-sdk';

export const usePurchases = () => {
  const { sdk, isInitialized, isAuthenticated } = usePersSDK();

  const createPaymentIntent = useCallback(async (
    amount: number, 
    currency: string, 
    receiptEmail: string, 
    description: string
  ) => {
    if (!isInitialized || !sdk) {
      throw new Error('SDK not initialized. Call initialize() first.');
    }
    
    try {
      const result = await sdk.purchases.createPaymentIntent(amount, currency, receiptEmail, description);
      return result;
    } catch (error) {
      console.error('Failed to create payment intent:', error);
      throw error;
    }
  }, [sdk, isInitialized]);

  const getActivePurchaseTokens = useCallback(async (): Promise<PaginatedResponseDTO<PurchaseTokenDTO>> => {
    if (!isInitialized || !sdk) {
      throw new Error('SDK not initialized. Call initialize() first.');
    }
    
    try {
      const result = await sdk.purchases.getActivePurchaseTokens();
      return result;
    } catch (error) {
      console.error('Failed to fetch active purchase tokens:', error);
      throw error;
    }
  }, [sdk, isInitialized]);

  const getAllUserPurchases = useCallback(async (): Promise<PaginatedResponseDTO<PurchaseDTO>> => {
    if (!isInitialized || !sdk) {
      throw new Error('SDK not initialized. Call initialize() first.');
    }
    if (!isAuthenticated) {
      throw new Error('SDK not authenticated. getAllUserPurchases requires authentication.');
    }
    
    try {
      const result = await sdk.purchases.getAllUserPurchases();
      return result;
    } catch (error) {
      console.error('Failed to fetch user purchases:', error);
      throw error;
    }
  }, [sdk, isInitialized, isAuthenticated]);

  return {
    createPaymentIntent,
    getActivePurchaseTokens,
    getAllUserPurchases,
    isAvailable: isInitialized && !!sdk?.purchases,
  };
};

export type PurchaseHook = ReturnType<typeof usePurchases>;