bookwiz.io / lib / hooks / usePortalSession.ts
usePortalSession.ts
Raw
import { useState } from 'react';
import { supabase } from '@/lib/supabase';

export function usePortalSession() {
  const [loading, setLoading] = useState(false);

  const createPortalSession = async () => {
    try {
      setLoading(true);
      // Get the current session to access the access token
      const { data: { session } } = await supabase.auth.getSession();
      
      if (!session?.access_token) {
        throw new Error('Not authenticated');
      }


      // Create a portal session
      const response = await fetch('/api/create-portal-session', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`,
        },
      });


      if (!response.ok) {
        const errorText = await response.text();
        console.error('API error response:', errorText);
        throw new Error(`API request failed: ${response.status} ${errorText}`);
      }

      const data = await response.json();

      if (data.error) {
        throw new Error(data.error);
      }

      if (!data.url) {
        throw new Error('No portal URL received');
      }

      
      // Try to redirect to the portal
      // First try in same window
      try {
        window.location.href = data.url;
      } catch (error) {
        console.warn('Same-window redirect failed, trying new tab:', error);
        // Fallback: open in new tab
        window.open(data.url, '_blank');
      }
    } catch (error) {
      console.error('Error creating portal session:', error);
      
      // Handle specific error cases with user-friendly messages
      let userMessage = 'Unable to open billing management. Please try again.';
      
      if (error instanceof Error) {
        if (error.message.includes('No subscription found')) {
          userMessage = 'You need an active subscription to manage billing. Please upgrade your plan first.';
        } else if (error.message.includes('Not authenticated')) {
          userMessage = 'Please log in again to manage your billing.';
        } else if (error.message.includes('API request failed')) {
          userMessage = 'Connection error. Please check your internet connection and try again.';
        }
      }
      
      // Show user-friendly error
      alert(userMessage);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    createPortalSession,
    loading,
  };
}