/**
 * Customer statement renderer + emailer — ar-aging-report (wave-12).
 *
 * `sendCustomerStatement` builds the statement for a given customer and
 * dispatches it via the Resend email adapter (sendEmail from @zync/notifications).
 *
 * The statement is rendered as an HTML email using the generic 'invoice-sent'
 * template with injected statement body. This avoids adding a new MJML template
 * file (which would require re-compilation) while still producing correct
 * RTL/Hebrew output.
 */
import type { Db } from '@zync/db/queries'
import { buildArAgingCustomerStatement } from '@zync/db/queries'
import type { Env } from '@zync/types'
import { sendEmail } from '@zync/notifications'

export interface SendStatementOptions {
  tenantId: string
  customerId: string
  asOf: string
  currency: string
  subject?: string
  message?: string
  locale?: 'he-IL' | 'en-US'
}

export interface SendStatementResult {
  sent: boolean
  skippedReason?: 'no_email' | 'no_outstanding' | 'customer_not_found'
}

function fmtAmount(amount: string): string {
  const n = parseFloat(amount)
  return n.toLocaleString('he-IL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function buildStatementBody(
  stmt: NonNullable<Awaited<ReturnType<typeof buildArAgingCustomerStatement>>>,
  locale: 'he-IL' | 'en-US',
): string {
  const isHe = locale === 'he-IL'
  const lines: string[] = []

  lines.push(isHe
    ? `שלום ${stmt.customerName},`
    : `Dear ${stmt.customerName},`)
  lines.push('')
  lines.push(isHe
    ? `להלן פירוט יתרות פתוחות נכון לתאריך ${stmt.asOf}:`
    : `Please find below your outstanding balance as of ${stmt.asOf}:`)
  lines.push('')

  for (const inv of stmt.invoices) {
    const num = inv.number ?? inv.id.slice(0, 8)
    const due = inv.dueDate ? ` (${isHe ? 'תאריך פירעון' : 'due'}: ${inv.dueDate})` : ''
    const ageNote = inv.ageDays > 0
      ? ` — ${inv.ageDays}${isHe ? ' ימים איחור' : ' days overdue'}`
      : ''
    lines.push(`${isHe ? 'חשבונית' : 'Invoice'} #${num}${due}${ageNote}: ${fmtAmount(inv.balance)} ${stmt.currency}`)
  }

  lines.push('')
  lines.push(`${isHe ? 'סה"כ לתשלום' : 'Total outstanding'}: ${fmtAmount(stmt.totalBalance)} ${stmt.currency}`)

  return lines.join('\n')
}

export async function sendCustomerStatement(
  db: Db,
  opts: SendStatementOptions,
  env: Env,
): Promise<SendStatementResult> {
  const { tenantId, customerId, asOf, currency, subject, message, locale = 'he-IL' } = opts

  // Build the customer statement data
  const stmt = await buildArAgingCustomerStatement(db, tenantId, customerId, asOf, currency)

  if (!stmt) {
    return { sent: false, skippedReason: 'customer_not_found' }
  }

  if (!stmt.customerEmail) {
    return { sent: false, skippedReason: 'no_email' }
  }

  if (stmt.invoices.length === 0) {
    return { sent: false, skippedReason: 'no_outstanding' }
  }

  const body = message ?? buildStatementBody(stmt, locale)
  const emailSubject = subject ?? (locale === 'he-IL'
    ? `דוח גיל חובות — ${stmt.asOf}`
    : `Account Statement — ${stmt.asOf}`)

  await sendEmail(
    {
      to: stmt.customerEmail,
      templateKey: 'invoice-sent',
      vars: {
        subject: emailSubject,
        title: emailSubject,
        body,
        actionButtons: '',
      },
      locale,
    },
    env,
  )

  return { sent: true }
}
