import { Resend } from 'resend' import { createClient } from '@/lib/supabase/server' import { newIncidentTemplate } from '@/lib/notifications/templates/new-incident' export async function sendNewIncidentEmail( incidentId: string, siteId: string, reference_no: string, incidentType: string, ): Promise { const supabase = await createClient() const { data: recipients } = await supabase .from('users') .select('email, name, role') .in('role', ['supervisor', 'hse']) .eq('site_id', siteId) if (!recipients || recipients.length === 0) return const to = recipients.map((r: { email: string }) => r.email).filter(Boolean) if (to.length === 0) return const { data: incident } = await supabase .from('incidents') .select('reported_at, sites (name), reporter:users!reported_by (name)') .eq('id', incidentId) .single() const siteName = (incident?.sites as { name: string } | null)?.name ?? 'Unknown Site' const reporterName = (incident?.reporter as { name: string } | null)?.name ?? 'Unknown' const reportedAt = incident?.reported_at ? new Date(incident.reported_at).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' }) : '-' const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000' const { subject, html, text } = newIncidentTemplate({ reference_no, incident_type: incidentType, site_name: siteName, reporter_name: reporterName, reported_at: reportedAt, site_url: siteUrl, incident_id: incidentId, }) const resend = new Resend(process.env.RESEND_API_KEY) const from = process.env.RESEND_FROM_EMAIL ?? 'onboarding@resend.dev' const { error } = await resend.emails.send({ from, to, subject, html, text }) if (error) console.error('Resend error:', error) }