import { useEffect, useState, useRef } from 'react'; import { supabase } from '@/integrations/supabase/client'; import { RealtimeChannel } from '@supabase/supabase-js'; interface UseRealtimeSubmissionsOptions { onInsert?: (payload: any) => void; onUpdate?: (payload: any) => void; onDelete?: (payload: any) => void; enabled?: boolean; } export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = {}) => { const { onInsert, onUpdate, onDelete, enabled = true } = options; const [channel, setChannel] = useState(null); // Use refs to store latest callbacks without triggering re-subscriptions const onInsertRef = useRef(onInsert); const onUpdateRef = useRef(onUpdate); const onDeleteRef = useRef(onDelete); // Update refs when callbacks change useEffect(() => { onInsertRef.current = onInsert; onUpdateRef.current = onUpdate; onDeleteRef.current = onDelete; }, [onInsert, onUpdate, onDelete]); useEffect(() => { if (!enabled) return; const realtimeChannel = supabase .channel('content-submissions-changes') .on( 'postgres_changes', { event: 'INSERT', schema: 'public', table: 'content_submissions', }, (payload) => { console.log('Submission inserted:', payload); onInsertRef.current?.(payload); } ) .on( 'postgres_changes', { event: 'UPDATE', schema: 'public', table: 'content_submissions', }, (payload) => { console.log('Submission updated:', payload); onUpdateRef.current?.(payload); } ) .on( 'postgres_changes', { event: 'DELETE', schema: 'public', table: 'content_submissions', }, (payload) => { console.log('Submission deleted:', payload); onDeleteRef.current?.(payload); } ) .subscribe((status) => { console.log('Submissions realtime status:', status); }); setChannel(realtimeChannel); return () => { console.log('Cleaning up submissions realtime subscription'); supabase.removeChannel(realtimeChannel); }; }, [enabled]); return { channel }; };