/**
 * Report email delivery — scheduled-reports (wave-15).
 *
 * Uses sendViaResend directly since SendEmailOptions does not support attachments.
 */
import type { Env } from '@zync/types'
import { sendViaResend } from '@zync/notifications'

import type { ReportScheduleRow } from '@zync/db/queries'
import type { ReportPeriod } from './schedule-math'

export interface ReportFile {
  filename: string
  contentType: string
  body: ArrayBuffer
}

/**
 * Send a report file to a single recipient via Resend.
 *
 * For `type: 'user'`, the recipient must supply their resolved email address
 * (resolved by the caller from the users table).
 */
export async function sendReportEmail(
  recipientEmail: string,
  file: ReportFile,
  schedule: Pick<ReportScheduleRow, 'name' | 'reportType'>,
  period: ReportPeriod,
  env: Env,
): Promise<void> {
  const esc = (s: string) =>
    s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')

  const subject = `${schedule.name} — ${period.label}`
  const html = `
    <p>Your scheduled report <strong>${esc(schedule.name)}</strong> for <strong>${esc(period.label)}</strong> is attached.</p>
    <p>Report type: ${esc(schedule.reportType)}<br>
    Period: ${esc(period.from)} – ${esc(period.to)}</p>
    <hr>
    <p style="font-size:12px;color:oklch(0.55 0.01 250);">You received this because you are subscribed to scheduled reports in Zync.
    To manage your subscriptions, visit your account settings.</p>
  `.trim()

  const text = `Your scheduled report "${schedule.name}" for ${period.label} is attached.\n\nReport type: ${schedule.reportType}\nPeriod: ${period.from} – ${period.to}`

  // Convert ArrayBuffer to base64 for Resend attachment
  const base64 = bufferToBase64(file.body)

  // Resend supports `attachments` in the payload even though it is not in the
  // typed interface — cast to allow the extra field.
  const payload = {
    from: 'Zync Reports <reports@zync.is>',
    to: recipientEmail,
    subject,
    html,
    text,
    attachments: [{ filename: file.filename, content: base64 }],
  } as Parameters<typeof sendViaResend>[0]

  await sendViaResend(payload, env.RESEND_API_KEY)
}

function bufferToBase64(buffer: ArrayBuffer): string {
  const bytes = new Uint8Array(buffer)
  let binary = ''
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]!)
  }
  return btoa(binary)
}
