import { describe, it, expect, vi, beforeEach } from 'vitest' import { createInAppNotifications } from '@/lib/notifications/in-app' import type { SupabaseClient } from '@supabase/supabase-js' function makeSupabaseMock(rpcResult: { error: unknown } = { error: null }) { return { rpc: vi.fn().mockResolvedValue(rpcResult), } as unknown as SupabaseClient } describe('createInAppNotifications', () => { beforeEach(() => { vi.clearAllMocks() }) it('calls create_in_app_notification RPC once per recipient', async () => { const supabase = makeSupabaseMock() const { created } = await createInAppNotifications(supabase, [ { userId: 'u1', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' }, { userId: 'u2', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' }, ]) expect(created).toBe(2) expect(supabase.rpc).toHaveBeenCalledTimes(2) expect(supabase.rpc).toHaveBeenCalledWith('create_in_app_notification', { p_recipient: 'u1', p_title: 'New incident', p_link: '/hse/incidents/i1', p_incident_id: 'i1', p_capa_id: null, }) }) it('skips entries missing userId or title', async () => { const supabase = makeSupabaseMock() const { created } = await createInAppNotifications(supabase, [ { userId: '', title: 'x' }, { userId: 'u1', title: '' }, ]) expect(created).toBe(0) expect(supabase.rpc).not.toHaveBeenCalled() }) it('counts only successful inserts when RPC errors', async () => { const supabase = makeSupabaseMock({ error: { message: 'boom' } }) const { created } = await createInAppNotifications(supabase, [ { userId: 'u1', title: 'x' }, ]) expect(created).toBe(0) }) it('deduplicates recipients for the same notification', async () => { const supabase = makeSupabaseMock() const { created } = await createInAppNotifications(supabase, [ { userId: 'u1', title: 'same', incidentId: 'i1' }, { userId: 'u1', title: 'same', incidentId: 'i1' }, ]) expect(created).toBe(1) expect(supabase.rpc).toHaveBeenCalledTimes(1) }) })