/**
 * Resend REST API client — system-communications-notifications.
 *
 * POSTs to the Resend /emails REST endpoint with RESEND_API_KEY.
 * No SMTP is used for system email — always the REST API.
 */

export interface ResendEmailPayload {
  from: string
  to: string | string[]
  subject: string
  html: string
  text?: string
  reply_to?: string
  /** Resend metadata tags — echoed back in webhook payloads for routing (e.g. invoice_id) */
  tags?: { name: string; value: string }[]
}

export interface ResendResponse {
  id: string
  from: string
  to: string[]
  created_at: string
}

/**
 * Send an email via the Resend REST API.
 * Throws on non-2xx response (caller should handle/log).
 */
export async function sendViaResend(
  payload: ResendEmailPayload,
  apiKey: string,
): Promise<ResendResponse> {
  const res = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  })

  if (!res.ok) {
    const body = await res.text()
    throw new Error(`Resend API error ${res.status}: ${body}`)
  }

  return res.json() as Promise<ResendResponse>
}
