/** * Supabase Realtime Client for MicroFunnel Studio * * Used for real-time message updates without polling. * Subscribes to INSERT events on the messages table. */ import { createClient } from '@supabase/supabase-js' // Supabase credentials from environment const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL || '' const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '' if (!SUPABASE_URL || !SUPABASE_ANON_KEY) { console.warn('⚠️ Supabase credentials missing. Realtime updates disabled.') console.warn('Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY in .env.local') } /** * Supabase client instance * * Features: * - Realtime subscriptions for messages table * - Auto-reconnect on connection loss * - Row-level security (RLS) via JWT token */ export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, { auth: { persistSession: false, // We use our own JWT auth autoRefreshToken: false, }, realtime: { params: { eventsPerSecond: 10, // Rate limiting }, }, }) /** * Subscribe to new messages for a specific conversation * * @param conversationId - UUID of the conversation * @param onNewMessage - Callback when new message arrives * @returns Unsubscribe function * * @example * const unsubscribe = subscribeToMessages(conversationId, (message) => { * console.log('New message:', message) * setMessages(prev => [...prev, message]) * }) * * // Cleanup on unmount * return () => unsubscribe() */ export function subscribeToMessages( conversationId: string, onNewMessage: (message: any) => void ) { console.log('🔌 Subscribing to Realtime for conversation:', conversationId) const channel = supabase .channel(`messages:${conversationId}`) .on( 'postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages', filter: `conversation_id=eq.${conversationId}`, }, (payload) => { console.log('✨ Realtime message received:', payload.new) onNewMessage(payload.new) } ) .subscribe((status) => { if (status === 'SUBSCRIBED') { console.log('✅ Realtime subscription active') } else if (status === 'CHANNEL_ERROR') { console.error('❌ Realtime subscription error') } else if (status === 'TIMED_OUT') { console.warn('⏱️ Realtime subscription timeout - will retry') } }) // Return unsubscribe function return () => { console.log('🔌 Unsubscribing from Realtime') supabase.removeChannel(channel) } } /** * Subscribe to lead updates (heat_score, status, psychotype changes) * * @param tenantId - UUID of the tenant * @param onLeadUpdate - Callback when lead data changes * @returns Unsubscribe function * * @example * const unsubscribe = subscribeToLeads(tenantId, (lead) => { * console.log('Lead updated:', lead) * setLeads(prev => prev.map(l => l.id === lead.id ? { ...l, ...lead } : l)) * }) * * // Cleanup on unmount * return () => unsubscribe() */ export function subscribeToLeads( tenantId: string, onLeadUpdate: (lead: any) => void ) { console.log('🔌 Subscribing to Lead updates for tenant:', tenantId) const channel = supabase .channel(`leads:${tenantId}`) .on( 'postgres_changes', { event: 'UPDATE', schema: 'public', table: 'leads', filter: `tenant_id=eq.${tenantId}`, }, (payload) => { console.log('🔄 Lead updated via Realtime:', payload.new) onLeadUpdate(payload.new) } ) .on( 'postgres_changes', { event: 'INSERT', schema: 'public', table: 'leads', filter: `tenant_id=eq.${tenantId}`, }, (payload) => { console.log('✨ New lead via Realtime:', payload.new) onLeadUpdate(payload.new) } ) .subscribe((status) => { if (status === 'SUBSCRIBED') { console.log('✅ Leads Realtime subscription active') } else if (status === 'CHANNEL_ERROR') { console.error('❌ Leads subscription error') } else if (status === 'TIMED_OUT') { console.warn('⏱️ Leads subscription timeout - will retry') } }) // Return unsubscribe function return () => { console.log('🔌 Unsubscribing from Leads Realtime') supabase.removeChannel(channel) } } /** * Check if Realtime is properly configured */ export function isRealtimeEnabled(): boolean { return !!(SUPABASE_URL && SUPABASE_ANON_KEY) }