import type { SupabaseClient } from '@supabase/supabase-js' export interface InAppNotification { userId: string title: string link?: string incidentId?: string capaId?: string } // Inserts go through the create_in_app_notification SECURITY DEFINER RPC: // notifications_log INSERT is RLS-restricted to elevated roles, but reporters // must still be able to trigger alerts to supervisors/HSE. export async function createInAppNotifications( supabase: SupabaseClient, notifications: InAppNotification[], ): Promise<{ created: number }> { const seen = new Set() let created = 0 for (const n of notifications) { if (!n.userId || !n.title) continue const key = `${n.userId}|${n.title}|${n.incidentId ?? ''}|${n.capaId ?? ''}` if (seen.has(key)) continue seen.add(key) const { error } = await supabase.rpc('create_in_app_notification', { p_recipient: n.userId, p_title: n.title, p_link: n.link ?? null, p_incident_id: n.incidentId ?? null, p_capa_id: n.capaId ?? null, }) if (error) { console.error('in-app notification error:', error) continue } created++ } return { created } }