// @vitest-environment node import { describe, it, expect, vi, beforeEach } from 'vitest' const { mockSend } = vi.hoisted(() => ({ mockSend: vi.fn(), })) vi.mock('resend', () => { function MockResend() {} MockResend.prototype.emails = { send: mockSend } return { Resend: MockResend } }) // Mock asAdmin: first call returns recipients, second returns incident+join rows let asAdminCallCount = 0 const mockRecipients = [ { email: 'supervisor@setiacorp.com' }, { email: 'hse@setiacorp.com' }, ] const mockIncidentRows = [{ reportedAt: new Date('2026-07-10T09:00:00Z'), siteName: 'SCW1', reporterName: 'John Doe', }] vi.mock('@/lib/db/with-user', () => ({ asAdmin: vi.fn().mockImplementation((fn: (db: unknown) => unknown) => { asAdminCallCount++ if (asAdminCallCount % 2 === 1) { // first call: recipients query return Promise.resolve(mockRecipients) } // second call: incident join query return Promise.resolve(mockIncidentRows) }), })) import { sendNewIncidentEmail } from '@/lib/notifications/email' beforeEach(() => { vi.clearAllMocks() asAdminCallCount = 0 mockSend.mockResolvedValue({ data: { id: 'email-123' }, error: null }) }) describe('sendNewIncidentEmail', () => { it('sends email to supervisor and hse users', async () => { await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss') expect(mockSend).toHaveBeenCalledTimes(1) const call = mockSend.mock.calls[0][0] expect(call.to).toEqual(expect.arrayContaining(['supervisor@setiacorp.com', 'hse@setiacorp.com'])) expect(call.subject).toContain('SCW1-202607-0001') }) it('does not send if no recipients', async () => { const { asAdmin } = await import('@/lib/db/with-user') vi.mocked(asAdmin).mockResolvedValueOnce([]) await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss') expect(mockSend).not.toHaveBeenCalled() }) })