import { supabase } from '@/integrations/supabase/client'; import { useEffect, useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useAuth } from '@/contexts/AuthContext'; export interface Notification { id: string; user_id: string; type: string; title: string; message: string; link: string | null; is_read: boolean; created_at: string; metadata: Record; } export const useNotifications = () => { const { user } = useAuth(); const queryClient = useQueryClient(); const { data: notifications, isLoading } = useQuery({ queryKey: ['notifications', user?.id], queryFn: async () => { if (!user) return []; const { data, error } = await supabase .from('notifications') .select('*') .eq('user_id', user.id) .order('created_at', { ascending: false }) .limit(50); if (error) throw error; return data as Notification[]; }, enabled: !!user, }); const unreadCount = notifications?.filter((n) => !n.is_read).length || 0; // Real-time subscription useEffect(() => { if (!user) return; const channel = supabase .channel('notifications') .on( 'postgres_changes', { event: 'INSERT', schema: 'public', table: 'notifications', filter: `user_id=eq.${user.id}`, }, (payload) => { queryClient.invalidateQueries({ queryKey: ['notifications', user.id] }); } ) .subscribe(); return () => { supabase.removeChannel(channel); }; }, [user, queryClient]); const markAsRead = useMutation({ mutationFn: async (notificationId: string) => { if (!user) throw new Error('Not authenticated'); const { error } = await supabase .from('notifications') .update({ is_read: true }) .eq('id', notificationId); if (error) throw error; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['notifications', user?.id] }); }, }); const markAllAsRead = useMutation({ mutationFn: async () => { if (!user) throw new Error('Not authenticated'); const { error } = await supabase .from('notifications') .update({ is_read: true }) .eq('user_id', user.id) .eq('is_read', false); if (error) throw error; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['notifications', user?.id] }); }, }); const deleteNotification = useMutation({ mutationFn: async (notificationId: string) => { if (!user) throw new Error('Not authenticated'); const { error } = await supabase .from('notifications') .delete() .eq('id', notificationId); if (error) throw error; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['notifications', user?.id] }); }, }); return { notifications: notifications || [], unreadCount, isLoading, markAsRead, markAllAsRead, deleteNotification, }; };