/**
 * Customer email on receipt issue — invoice-receipt-document (spec 179, Flow A/B step 5).
 *
 * Reuses @zync/notifications sendEmail + invoice_paid_receipt template (same path as
 * the planned payment-confirmation receipt email).
 */
import { sendEmail } from '@zync/notifications'
import type { Db } from '@zync/db/queries'
import type { Env } from '@zync/types'
import type { ReceiptObject } from '@zync/types'
import { resolveCustomerPrimaryEmail } from './payment-link'
import { loadInvoiceRenderIdentity } from '../lib/invoice-snapshot'

export interface SendReceiptIssuedEmailResult {
  sent: boolean
  skipped?: string
  recipient?: string
}

/**
 * Send the customer a receipt email with receipt number and PDF link.
 * Non-fatal when skipped (no primary email).
 */
export async function sendReceiptIssuedEmail(
  db: Db,
  env: Env,
  tenantId: string,
  receipt: ReceiptObject,
): Promise<SendReceiptIssuedEmailResult> {
  const recipientEmail = await resolveCustomerPrimaryEmail(db, tenantId, receipt.customerId)
  if (!recipientEmail) {
    return { sent: false, skipped: 'no_recipient_email' }
  }

  const identity = await loadInvoiceRenderIdentity(db, tenantId, receipt.customerId)
  const baseUrl = env.APP_BASE_URL ?? 'https://app.zync.is'
  const pdfUrl = `${baseUrl}/api/portal/receipts/${receipt.id}/pdf`
  const receiptNumber = receipt.receiptNumber ?? receipt.id
  const amount = `${receipt.currency} ${receipt.amount}`
  const paidDate = receipt.issuedAt?.slice(0, 10) ?? new Date().toISOString().slice(0, 10)

  const subject =
    identity.locale === 'he-IL'
      ? `קבלה ${receiptNumber} — ${identity.tenantName}`
      : `Receipt ${receiptNumber} — ${identity.tenantName}`

  const body =
    identity.locale === 'he-IL'
      ? `תודה על התשלום.\n\nקבלה מספר ${receiptNumber}\nסכום: ${amount}\nתאריך: ${paidDate}`
      : `Thank you for your payment.\n\nReceipt ${receiptNumber}\nAmount: ${amount}\nDate: ${paidDate}`

  const ctaLabel = identity.locale === 'he-IL' ? 'הורד PDF' : 'Download PDF'
  const actionButtons = `<a href="${pdfUrl}" style="display:inline-block;padding:12px 24px;background:oklch(39% 0.18 302);color:oklch(100% 0 0);text-decoration:none;border-radius:4px;font-size:16px;">${ctaLabel}</a>`

  await sendEmail(
    {
      to: recipientEmail,
      templateKey: 'invoice_paid_receipt',
      locale: identity.locale,
      vars: {
        subject,
        title: subject,
        body,
        actionButtons,
        invoiceNumber: receiptNumber,
        tenantName: identity.tenantName,
        customerName: identity.customerName,
        amount,
        paidDate,
      },
      tags: { receipt_id: receipt.id },
    },
    env,
  )

  return { sent: true, recipient: recipientEmail }
}
