import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import type { Attachment } from '@prisma/client';
import { CURRENCY_SYMBOLS, Decimal, sum } from '@rms/domain';
import Handlebars from 'handlebars';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import { STAFF_EVIDENCE } from '../attachments/attachment.service';
import { StorageService } from '../attachments/storage.service';
import { amountInWords } from '../common/amount-words';
import { hkIsoDay } from '../common/hk-date';
import { leaseLetterhead, letterheadFor, letterheadPropertySelect, type Letterhead } from '../common/letterhead';
import { addressOf, buildingOf, premisesLines, propertiesOf } from '../common/lease-premises';
import { defaultCollectionAccount } from '../ledger/bank-accounts';
import { PrismaService } from '../prisma/prisma.service';
import type { Statement, StatementAging, StatementRow } from '../reports/reports.types';
import { printedParticulars, withCompanyEmail, withTenantContact } from './debit-note-print';
import { DEFAULT_TEMPLATES } from './default-templates';
import { PdfService } from './pdf.service';

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const pad = (n: number) => String(n).padStart(2, '0');

/** dd/MM/yyyy — the format on the debit note's Period columns. */
function ddmmyyyy(v: unknown): string {
  if (!v) return '';
  const d = new Date(v as string);
  if (Number.isNaN(d.getTime())) return '';
  return `${pad(d.getUTCDate())}/${pad(d.getUTCMonth() + 1)}/${d.getUTCFullYear()}`;
}

/** dd-MMM-yy — the format on the "Date :" line. */
function ddMMMyy(v: unknown): string {
  if (!v) return '';
  const d = new Date(v as string);
  if (Number.isNaN(d.getTime())) return '';
  return `${pad(d.getUTCDate())}-${MONTHS[d.getUTCMonth()]}-${String(d.getUTCFullYear()).slice(2)}`;
}

/** yyyyMMMdd, e.g. 2024MAR07 — the format on the ERP's receipt. */
function dateCompact(v: unknown): string {
  if (!v) return '';
  const d = new Date(v as string);
  if (Number.isNaN(d.getTime())) return '';
  return `${d.getUTCFullYear()}${MONTHS[d.getUTCMonth()].toUpperCase()}${pad(d.getUTCDate())}`;
}

function thousands(v: unknown): string {
  const n = Number(v ?? 0);
  if (!Number.isFinite(n)) return String(v ?? '');
  const [int, frac = '00'] = Math.abs(n).toFixed(2).split('.');
  return `${n < 0 ? '-' : ''}${int.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}.${frac}`;
}

const hb = Handlebars.create();
hb.registerHelper('money', thousands);
hb.registerHelper('date', ddmmyyyy);
hb.registerHelper('dateShort', ddMMMyy);
hb.registerHelper('dateCompact', dateCompact);
hb.registerHelper('eq', (a: unknown, b: unknown) => a === b);

const esc = (s: string): string =>
  String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c);

/** Page frame + evidence-page styling. The template owns its own look; this only
 * provides the paper rules both it and the appended evidence pages rely on. */
const SKELETON_CSS = `
  * { box-sizing: border-box; }
  body { margin: 0; font-family: "Helvetica Neue", Arial, "PingFang HK", "Microsoft JhengHei", "Noto Sans TC", sans-serif; color: #111; }
  .page { page-break-after: always; }
  .page:last-child { page-break-after: auto; }
  .ev h2 { font-size: 12pt; margin: 8mm 0 6mm; }
  .ev .meter { break-inside: avoid; margin-bottom: 10mm; }
  .ev .meter-head { display: flex; justify-content: space-between; font-size: 10.5pt;
                    border-bottom: 1px solid #000; padding-bottom: 1mm; margin-bottom: 3mm; }
  .ev .meter-head b { text-decoration: underline; }
  .ev .shots { display: flex; gap: 8mm; align-items: flex-start; }
  .ev .shot { flex: 1; font-size: 9pt; }
  .ev .shot .lbl { color: #444; }
  .ev .shot .val { border: 1px solid #000; display: inline-block; padding: 0 2mm; min-width: 24mm; margin-bottom: 2mm; }
  .ev .shot img { display: block; width: 100%; max-height: 78mm; object-fit: contain; border: 1px solid #ccc; }
  .ev .usage { text-align: right; font-size: 9pt; }
  .ev h2:first-child { margin-top: 0; }
  .ev .docs { display: flex; flex-wrap: wrap; gap: 6mm; }
  .ev .docs figure { margin: 0; width: calc(50% - 3mm); break-inside: avoid; }
  .ev .docs img { width: 100%; max-height: 95mm; object-fit: contain; border: 1px solid #ccc; }
  .ev figcaption, .ev .file { font-size: 8.5pt; color: #444; margin-top: 1mm; }
  .ev .file { border: 1px dashed #999; padding: 3mm; }
`;

export interface InvoiceDocumentContext {
  /** WHOSE note this is — the letterhead it is printed under. The organisation
   *  unless the property says its owning company, which is why the field keeps
   *  its name: every template in the field already prints {{org.name}}, and what
   *  changed is which company that resolves to, not where it appears. */
  org: { name: string; nameZh: string | null; address: string | null; tel: string | null; fax: string | null; email: string | null; attention: string | null };
  doc: { number: string; isDraft: boolean; date: Date; dueDate: Date; period: string; currency: string; status: string };
  /** Address, phone and email only where the tenant's record says to print them. */
  tenant: { name: string; nameZh: string | null; attention: string | null; phone: string | null; email: string | null; address: string | null };
  property: { name: string; address: string | null; units: string[]; addressLines: string[] };
  lease: { reference: string };
  charges: DocumentLine[];
  credits: DocumentLine[];
  lines: DocumentLine[];
  /** The same charges with each meter reading's per-unit shares folded into one
   * row — how the paper note reads: "Water · units A,B,C,D,E · 71.5%". */
  groups: DocumentGroup[];
  total: string;
  payee: { accountName: string; bankName: string; accountNumber: string };
}

export interface DocumentGroup {
  description: string;
  /** "A, B, C, D, E" when a meter's cost was split; null otherwise. */
  units: string | null;
  /** Combined share of the meter these units carry, e.g. "71.5%". */
  serial: string | null;
  deduction: string | null;
  /** "5000 → 5600" for a metered group; null otherwise. */
  reading: string | null;
  from: Date | null;
  to: Date | null;
  amount: string;
  count: number;
  /** A credit — the paper note lists these under "Less :". */
  negative: boolean;
}

interface DocumentLine {
  id: string;
  description: string;
  note: string | null;
  kind: string;
  from: Date | null;
  to: Date | null;
  amount: string;
  meter: Record<string, unknown> | null;
  /** The standard figures that took effect with this charge, when it is the
   *  first to bill them — their notices go on the note. */
  standardChanged: string[];
}

/** Folds consecutive lines from the same meter reading into one row carrying the
 * units, the meter and the subtotal — one meter across five flats is one charge
 * on paper, not five. Everything else passes through. */
function groupLines(lines: DocumentLine[]): DocumentGroup[] {
  const out: DocumentGroup[] = [];
  let bucket: DocumentLine[] = [];
  const flush = () => {
    if (bucket.length === 0) return;
    const first = bucket[0];
    const meter = first.meter as { unitName?: string; readingStart?: string; readingEnd?: string; serialNo?: string; deductionNote?: string } | null;
    const amount = bucket.reduce((s, l) => s + Number(l.amount), 0);
    out.push({
      // Drop the per-unit suffix the line description carries — the units are
      // named on their own field here.
      description: printedParticulars(meter ? first.description.replace(/\s*·\s*[^·]*\(.*\)\s*$/, '') : first.description),
      units: meter ? bucket.map((l) => (l.meter as { unitName?: string } | null)?.unitName).filter(Boolean).join(', ') : null,
      serial: meter ? String(meter.serialNo ?? '') : null,
      // How the figure was arrived at, when sub-meters were taken off it.
      deduction: meter && meter.deductionNote ? String(meter.deductionNote) : null,
      reading: meter ? `${meter.readingStart} → ${meter.readingEnd}` : null,
      from: first.from,
      to: first.to,
      amount: amount.toFixed(2),
      count: bucket.length,
      negative: amount < 0,
    });
    bucket = [];
  };
  let key: string | null = null;
  for (const l of lines) {
    const readingId = (l.meter as { meterReadingId?: string } | null)?.meterReadingId ?? null;
    const next = readingId ? `meter:${readingId}` : `line:${l.id}`;
    if (next !== key) {
      flush();
      key = next;
    }
    bucket.push(l);
  }
  flush();
  return out;
}

/** Everything a statement template can reference — one lease's account for the
 *  period, under the letterhead its debit notes would print today. */
export interface StatementDocumentContext {
  org: Letterhead;
  statement: { from: string; to: string; currency: string };
  tenant: { name: string; nameZh: string | null; code: string | null; attention: string | null; phone: string | null; email: string | null };
  lease: { reference: string };
  property: { name: string; address: string | null; units: string[]; addressLines: string[] };
  rows: StatementRow[];
  opening: string;
  debit: string;
  credit: string;
  closing: string;
  aging: StatementAging;
  deposit: string;
  unallocated: string;
}

/** Everything a receipt template can reference — one approved payment, under
 *  the letterhead of the notes it paid. Dates are Hong Kong days (yyyy-mm-dd). */
export interface ReceiptDocumentContext {
  org: Letterhead;
  receipt: {
    number: string;
    date: string;
    kind: 'RECEIPT' | 'DEPOSIT_RECEIPT';
    currency: string;
    /** "HK$" — how the figures are printed. */
    symbol: string;
    status: string;
    /** Approved, then the payment bounced. */
    dishonoured: boolean;
    method: string | null;
    reference: string | null;
    /** The settlement method's receipt remark. */
    remark: string | null;
  };
  tenant: { name: string; nameZh: string | null; code: string | null; attention: string | null; phone: string | null; email: string | null };
  lease: { reference: string };
  property: { name: string; address: string | null; units: string[]; addressLines: string[] };
  /** The debit notes this payment settled, and how much of each. None for a deposit receipt. */
  invoices: { number: string; date: string | null; amount: string }[];
  /** What the notes were settled by — or a deposit receipt's amount. */
  total: string;
  applied: string;
  /** All that was received: the receipt and the overpaid part held under deposit receipts. */
  actual: string;
  excess: { number: string; amount: string }[];
  /** A deposit receipt: paid before its note, so there is no note to list. */
  advance: boolean;
  /** The total in words, "HONG KONG DOLLARS … ONLY". */
  words: string;
}

/** A lease as a document's address block and letterhead read it. */
const leaseForDocument = {
  select: {
    reference: true,
    units: {
      select: {
        unit: { select: { id: true, name: true, property: { select: { name: true, address: true, ...letterheadPropertySelect } } } },
      },
    },
  },
} as const;

@Injectable()
export class DocumentService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly storage: StorageService,
    private readonly pdf: PdfService,
  ) {}

  // ── Templates ─────────────────────────────────────────────

  /** The org's template for a document kind, seeded from the shipped default the
   * first time it is asked for — so a fresh install prints without any setup. */
  async template(organizationId: string, docType = 'INVOICE') {
    const found = await this.prisma.documentTemplate.findUnique({
      where: { organizationId_docType: { organizationId, docType } },
    });
    if (found) {
      // A template saved before the letterhead printed the company email, or
      // before the tenant's address and email were printed, still has the old
      // lines. Bring those forward; anything the office has rewritten (no exact
      // match) is left as they saved it.
      if (docType === 'INVOICE') {
        const body = withTenantContact(withCompanyEmail(found.body));
        if (body !== found.body) return this.prisma.documentTemplate.update({ where: { id: found.id }, data: { body } });
      }
      return found;
    }
    const shipped = DEFAULT_TEMPLATES[docType] ?? DEFAULT_TEMPLATES.INVOICE;
    return this.prisma.documentTemplate.create({
      data: { organizationId, docType, name: shipped.name, body: shipped.body },
    });
  }

  async saveTemplate(input: { organizationId: string; docType: string; name?: string; body: string; pageSize?: string; marginsMm?: string }) {
    const current = await this.template(input.organizationId, input.docType);
    return this.prisma.documentTemplate.update({
      where: { id: current.id },
      data: {
        name: input.name ?? current.name,
        body: input.body,
        pageSize: input.pageSize ?? current.pageSize,
        marginsMm: input.marginsMm ?? current.marginsMm,
      },
    });
  }

  /** Put the shipped layout back — the way out of a template edited into a mess. */
  async resetTemplate(organizationId: string, docType = 'INVOICE') {
    const current = await this.template(organizationId, docType);
    const shipped = DEFAULT_TEMPLATES[docType] ?? DEFAULT_TEMPLATES.INVOICE;
    return this.prisma.documentTemplate.update({
      where: { id: current.id },
      data: { name: shipped.name, body: shipped.body, pageSize: 'A4', marginsMm: '12,12,12,12' },
    });
  }

  // ── Context ───────────────────────────────────────────────

  /** Everything a debit-note template can reference. Reads live data, so the
   * same call serves a DRAFT preview and a re-print of an issued note; a note
   * that has been issued reports its frozen payee instead of the live one. */
  async invoiceContext(organizationId: string, invoiceId: string): Promise<InvoiceDocumentContext> {
    const invoice = await this.prisma.invoice.findFirst({
      where: { id: invoiceId, organizationId },
      include: {
        lines: { orderBy: { sortOrder: 'asc' } },
        bankAccount: true,
        lease: {
          include: {
            tenant: true,
            units: { include: { unit: { select: { id: true, name: true, property: { include: { landlord: letterheadPropertySelect.landlord } } } } } },
          },
        },
      },
    });
    if (!invoice) throw new NotFoundException('Debit note not found');

    const org = await this.prisma.organization.findFirstOrThrow({ where: { id: organizationId } });

    // Split billing: a note scoped to some units names only those — and the
    // address of the purchases they are on.
    const scope = (invoice.unitScope as string[] | null) ?? null;
    const billed = invoice.lease.units.filter((u) => !scope || scope.includes(u.unit.id));
    const unitNames = billed.map((u) => u.unit.name);
    const premises = { name: buildingOf(propertiesOf(billed)), address: addressOf(propertiesOf(billed)) };

    const toLine = (l: (typeof invoice.lines)[number]): DocumentLine => {
      const meta = (l.meta ?? null) as Record<string, unknown> | null;
      const meter = meta && typeof meta === 'object' && 'meterReadingId' in meta ? meta : null;
      return {
        id: l.id,
        description: l.description,
        note: meter
          ? `Meter ${String(meter.serialNo ?? '')} — ${String(meter.readingStart ?? '')} → ${String(meter.readingEnd ?? '')}${meter.deductionNote ? ` (${String(meter.deductionNote)})` : ''}`
          : null,
        kind: l.kind,
        from: l.periodStart,
        to: l.periodEnd,
        amount: l.amount.toFixed(2),
        meter,
        standardChanged: Array.isArray(meta?.standardChanged) ? meta.standardChanged.filter((v): v is string => typeof v === 'string') : [],
      };
    };

    const lines = invoice.lines.map(toLine);
    const total = sum(invoice.lines.map((l) => l.amount.toString()));

    // A payee frozen at issue wins over the live bank account, so a re-print of
    // an old note never shows today's banking details.
    const snapshot = (invoice.payeeSnapshot ?? null) as { accountName?: string; bankName?: string; accountNumber?: string } | null;
    const fallback = invoice.bankAccount ?? (await defaultCollectionAccount(this.prisma, organizationId));

    const addressLines = premisesLines(unitNames, premises.name, premises.address);

    // Whose name heads the note. Frozen at issue like the payee above, so a
    // re-print shows the company the tenant was actually billed by; a DRAFT has
    // nothing frozen and shows what issuing it now would print. `fax` is read
    // defensively because the organisation record has no such column yet — kept
    // as its own field so a template can print "Fax :" without the address
    // having to smuggle it in.
    const letterhead = letterheadFor({
      org: { ...org, fax: (org as { fax?: string | null }).fax ?? null },
      properties: propertiesOf(invoice.lease.units),
      snapshot: invoice.letterheadSnapshot,
      issued: invoice.number !== null,
    });

    return {
      org: letterhead,
      doc: {
        number: invoice.number ?? `DRAFT-${invoice.id.slice(-6).toUpperCase()}`,
        isDraft: invoice.number === null,
        date: invoice.issueDate ?? new Date(),
        dueDate: invoice.dueDate,
        period: invoice.billingPeriod,
        currency: invoice.currency,
        status: invoice.status,
      },
      tenant: {
        name: invoice.lease.tenant.name,
        nameZh: invoice.lease.tenant.nameZh,
        attention: invoice.lease.tenant.attention,
        // An email kept for notices, say, need not be on the bill.
        phone: invoice.lease.tenant.printPhone ? invoice.lease.tenant.phone : null,
        email: invoice.lease.tenant.printEmail ? invoice.lease.tenant.email : null,
        address: invoice.lease.tenant.printAddress ? invoice.lease.tenant.address : null,
      },
      property: { name: premises.name, address: premises.address, units: unitNames, addressLines },
      lease: { reference: invoice.lease.reference },
      charges: lines.filter((l) => Number(l.amount) >= 0),
      credits: lines.filter((l) => Number(l.amount) < 0),
      lines,
      groups: groupLines(lines),
      total: total.toFixed(2),
      payee: {
        accountName: snapshot?.accountName ?? fallback?.accountName ?? org.name,
        bankName: snapshot?.bankName ?? fallback?.bankName ?? '',
        accountNumber: snapshot?.accountNumber ?? fallback?.accountNumber ?? '',
      },
    };
  }

  /** Everything a receipt template can reference. Only a payment that was
   *  approved has a receipt; one that bounced afterwards keeps it, stamped.
   *  Like a debit note it is drawn from live data — nothing on an approved
   *  receipt changes but its status. */
  async receiptContext(organizationId: string, receiptId: string): Promise<ReceiptDocumentContext> {
    const receipt = await this.prisma.receipt.findFirst({
      where: { id: receiptId, organizationId },
      include: {
        settlementMethod: { select: { nameEn: true, receiptRemark: true } },
        lease: leaseForDocument,
        overpayments: { select: { number: true, amount: true, status: true }, orderBy: { number: 'asc' } },
        allocations: {
          orderBy: { createdAt: 'asc' },
          include: {
            items: {
              orderBy: { id: 'asc' },
              include: { invoice: { select: { number: true, issueDate: true, unitScope: true, letterheadSnapshot: true, lease: leaseForDocument } } },
            },
          },
        },
      },
    });
    if (!receipt) throw new NotFoundException('Receipt not found');
    // One bank-in, one receipt: the overpaid part is its Actual Receipt and Excess lines.
    if (receipt.sourceReceiptId) throw new BadRequestException('The overpaid part of a payment is printed on the receipt for that payment');
    if (receipt.status !== 'APPROVED' && receipt.status !== 'BOUNCED') {
      throw new BadRequestException('A receipt is issued once the payment is approved');
    }

    const org = await this.prisma.organization.findFirstOrThrow({ where: { id: organizationId } });
    const party = { ...org, fax: (org as { fax?: string | null }).fax ?? null };
    const tenant = await this.prisma.tenant.findFirstOrThrow({ where: { id: receipt.tenantId }, include: { codes: true } });

    const items = receipt.kind === 'RECEIPT' ? receipt.allocations.flatMap((a) => a.items) : [];
    const first = items[0]?.invoice ?? null;
    // Headed and addressed as the first note it paid was — a payment over
    // several notes is one tenant's, and they are one company's as a rule. A
    // deposit receipt has no note yet: it reads as its lease's would today.
    const lease = first?.lease ?? receipt.lease;
    if (!lease) throw new NotFoundException('Receipt not found');
    const scope = (first?.unitScope as string[] | null) ?? null;
    const billed = lease.units.filter((u) => !scope || scope.includes(u.unit.id));
    const properties = propertiesOf(lease.units);
    const premises = propertiesOf(billed);
    const letterhead = first
      ? letterheadFor({ org: party, properties, snapshot: first.letterheadSnapshot, issued: first.number !== null })
      : leaseLetterhead(party, properties);
    const landlord = properties.find((p) => p.landlord)?.landlord ?? null;

    const amount = new Decimal(receipt.amount.toString());
    // The overpaid part moves with the receipt: approved and bounced with it.
    const excess = receipt.overpayments.filter((o) => o.status === receipt.status);
    const total = items.length ? sum(items.map((i) => i.amount.toString())) : amount;
    const unitNames = billed.map((u) => u.unit.name);
    const building = buildingOf(premises);
    const address = addressOf(premises);

    return {
      org: letterhead,
      receipt: {
        number: receipt.number,
        date: hkIsoDay(receipt.receivedDate),
        kind: receipt.kind,
        currency: receipt.currency,
        symbol: CURRENCY_SYMBOLS[receipt.currency] ?? receipt.currency,
        status: receipt.status,
        dishonoured: receipt.status === 'BOUNCED',
        method: receipt.settlementMethod?.nameEn ?? null,
        reference: receipt.reference,
        remark: receipt.settlementMethod?.receiptRemark ?? null,
      },
      tenant: {
        name: tenant.name,
        nameZh: tenant.nameZh,
        code: (landlord && tenant.codes.find((c) => c.landlordId === landlord.id)?.code) ?? null,
        attention: tenant.attention,
        phone: tenant.phone,
        email: tenant.email,
      },
      lease: { reference: lease.reference },
      property: { name: building, address, units: unitNames, addressLines: premisesLines(unitNames, building, address) },
      invoices: items.map((i) => ({
        number: i.invoice.number ?? '',
        date: i.invoice.issueDate ? hkIsoDay(i.invoice.issueDate) : null,
        amount: i.amount.toFixed(2),
      })),
      total: total.toFixed(2),
      applied: amount.toFixed(2),
      actual: sum([amount.toString(), ...excess.map((o) => o.amount.toString())]).toFixed(2),
      excess: excess.map((o) => ({ number: o.number, amount: o.amount.toFixed(2) })),
      advance: receipt.kind === 'DEPOSIT_RECEIPT',
      words: amountInWords(total.toFixed(2), receipt.currency),
    };
  }

  // ── Rendering ─────────────────────────────────────────────

  /** Full print-ready HTML: the template's page, then one evidence page per
   * meter reading behind a charge and one for the charges' own attachments. */
  async invoiceHtml(
    organizationId: string,
    invoiceId: string,
    bodyOverride?: string,
  ): Promise<{ html: string; pageSize: string; marginsMm: string; appendPdfs: Attachment[] }> {
    const [ctx, tpl] = await Promise.all([
      this.invoiceContext(organizationId, invoiceId),
      this.template(organizationId, 'INVOICE'),
    ]);

    let rendered: string;
    try {
      rendered = hb.compile(bodyOverride ?? tpl.body, { noEscape: false })(ctx);
    } catch (err) {
      // A broken template must not read as a broken system — show the fault on
      // the page so the editor's preview tells the author what to fix.
      rendered = `<pre style="color:#b91c1c;font:12px monospace;white-space:pre-wrap">Template error: ${esc(
        err instanceof Error ? err.message : String(err),
      )}</pre>`;
    }

    const evidence = await this.evidencePages(organizationId, invoiceId, ctx);
    const html = `<!doctype html><html><head><meta charset="utf-8"><style>${SKELETON_CSS}</style></head><body>` +
      `<section class="page">${rendered}</section>${evidence.html}</body></html>`;
    return { html, pageSize: tpl.pageSize, marginsMm: tpl.marginsMm, appendPdfs: evidence.appendPdfs };
  }

  async invoicePdf(organizationId: string, invoiceId: string, bodyOverride?: string): Promise<Buffer> {
    const { html, pageSize, marginsMm, appendPdfs } = await this.invoiceHtml(organizationId, invoiceId, bodyOverride);
    const pdf = await this.pdf.render(html, { pageSize, marginsMm });
    const merged = appendPdfs.length ? await this.appendPages(pdf, appendPdfs) : pdf;
    return this.stampPageNumbers(merged);
  }

  /** The statements as one PDF, each from a new page, in the order given. The
   *  figures come from the reports service; this only lays them out. */
  async statementsPdf(organizationId: string, statements: Statement[], range: { from: string; to: string }, bodyOverride?: string): Promise<Buffer> {
    const { html, pageSize, marginsMm } = await this.statementsHtml(organizationId, statements, range, bodyOverride);
    return this.pdf.render(html, { pageSize, marginsMm });
  }

  async statementsHtml(
    organizationId: string,
    statements: Statement[],
    range: { from: string; to: string },
    bodyOverride?: string,
  ): Promise<{ html: string; pageSize: string; marginsMm: string }> {
    const [contexts, tpl] = await Promise.all([this.statementContexts(organizationId, statements, range), this.template(organizationId, 'STATEMENT')]);
    let pages: string[];
    try {
      const render = hb.compile(bodyOverride ?? tpl.body, { noEscape: false });
      pages = contexts.map((ctx) => render(ctx));
    } catch (err) {
      // As with a debit note: a broken template shows its fault on the page.
      pages = [`<pre style="color:#b91c1c;font:12px monospace;white-space:pre-wrap">Template error: ${esc(err instanceof Error ? err.message : String(err))}</pre>`];
    }
    const html = `<!doctype html><html><head><meta charset="utf-8"><style>${SKELETON_CSS}</style></head><body>` +
      pages.map((p) => `<section class="page">${p}</section>`).join('') + `</body></html>`;
    return { html, pageSize: tpl.pageSize, marginsMm: tpl.marginsMm };
  }

  private async statementContexts(organizationId: string, statements: Statement[], range: { from: string; to: string }): Promise<StatementDocumentContext[]> {
    const org = await this.prisma.organization.findFirstOrThrow({ where: { id: organizationId } });
    const leases = await this.prisma.lease.findMany({
      where: { id: { in: statements.map((s) => s.leaseId) }, organizationId },
      select: { id: true, units: { select: { unit: { select: { property: { select: letterheadPropertySelect } } } } } },
    });
    const propertiesFor = new Map(leases.map((l) => [l.id, propertiesOf(l.units)]));
    return statements.map((s) => ({
      // What the lease's notes would print today — a statement is not frozen.
      org: leaseLetterhead({ ...org, fax: (org as { fax?: string | null }).fax ?? null }, propertiesFor.get(s.leaseId) ?? []),
      statement: { from: range.from, to: range.to, currency: s.currency },
      tenant: { name: s.tenantName, nameZh: s.tenantNameZh, code: s.tenantCode, attention: s.attention, phone: s.phone, email: s.email },
      lease: { reference: s.leaseReference },
      property: { name: s.building, address: s.address, units: s.units, addressLines: premisesLines(s.units, s.building, s.address) },
      rows: s.rows,
      opening: s.opening,
      debit: s.debit,
      credit: s.credit,
      closing: s.closing,
      aging: s.aging,
      deposit: s.deposit,
      unallocated: s.unallocated,
    }));
  }

  /** The receipt, then the proof of payment the tenant or office uploaded with
   *  it — images on a page of their own, PDFs' own pages after that. The
   *  office's private evidence for refusing a payment is not the tenant's to
   *  read, so it stays off. A deposit receipt overpaid on another receipt
   *  shares that receipt's proof: it is the same bank-in. */
  async receiptHtml(
    organizationId: string,
    receiptId: string,
    bodyOverride?: string,
  ): Promise<{ html: string; pageSize: string; marginsMm: string; appendPdfs: Attachment[] }> {
    const [ctx, tpl] = await Promise.all([this.receiptContext(organizationId, receiptId), this.template(organizationId, 'RECEIPT')]);
    let rendered: string;
    try {
      rendered = hb.compile(bodyOverride ?? tpl.body, { noEscape: false })(ctx);
    } catch (err) {
      // As with a debit note: a broken template shows its fault on the page.
      rendered = `<pre style="color:#b91c1c;font:12px monospace;white-space:pre-wrap">Template error: ${esc(err instanceof Error ? err.message : String(err))}</pre>`;
    }

    const proofs = await this.prisma.attachment.findMany({
      where: {
        organizationId,
        ownerType: 'RECEIPT',
        ownerId: receiptId,
        OR: [{ role: null }, { role: { not: STAFF_EVIDENCE } }],
      },
      orderBy: { createdAt: 'asc' },
    });
    const appendPdfs: Attachment[] = [];
    const figures: string[] = [];
    for (const file of proofs) figures.push(await this.figureOf(file, esc(file.caption || file.filename), appendPdfs, 'receipt'));
    const evidence = figures.length
      ? `<section class="page ev"><h2>Payment proof — ${esc(ctx.receipt.number)}</h2><div class="docs">${figures.join('')}</div></section>`
      : '';

    const html = `<!doctype html><html><head><meta charset="utf-8"><style>${SKELETON_CSS}</style></head><body>` +
      `<section class="page">${rendered}</section>${evidence}</body></html>`;
    return { html, pageSize: tpl.pageSize, marginsMm: tpl.marginsMm, appendPdfs };
  }

  async receiptPdf(organizationId: string, receiptId: string, bodyOverride?: string): Promise<Buffer> {
    const { html, pageSize, marginsMm, appendPdfs } = await this.receiptHtml(organizationId, receiptId, bodyOverride);
    const pdf = await this.pdf.render(html, { pageSize, marginsMm });
    return appendPdfs.length ? this.appendPages(pdf, appendPdfs) : pdf;
  }

  /** A notice filed as a PDF cannot be drawn on a page of the note, so its own
   *  pages follow the note's. One that will not open is skipped — it is named
   *  on the notice page, and must not sink the note. */
  private async appendPages(pdf: Buffer, files: Attachment[]): Promise<Buffer> {
    const doc = await PDFDocument.load(pdf);
    for (const file of files) {
      try {
        const src = await PDFDocument.load(await this.storage.read(file.storageKey), { ignoreEncryption: true });
        for (const page of await doc.copyPages(src, src.getPageIndices())) doc.addPage(page);
      } catch {
        // unreadable or missing: named on the notice page all the same
      }
    }
    return Buffer.from(await doc.save());
  }

  /** "1 / 3" in the bottom margin of every page. Counted on the finished PDF,
   *  so the total is the whole debit note — the note itself and the evidence
   *  that follows it. */
  private async stampPageNumbers(pdf: Buffer): Promise<Buffer> {
    const doc = await PDFDocument.load(pdf);
    const font = await doc.embedFont(StandardFonts.TimesRoman);
    const pages = doc.getPages();
    const total = pages.length;
    const size = 9;
    for (let i = 0; i < total; i++) {
      const page = pages[i];
      const text = `${i + 1} / ${total}`;
      page.drawText(text, {
        x: page.getWidth() - font.widthOfTextAtSize(text, size) - 34,
        y: 16,
        size,
        font,
        color: rgb(0.1, 0.1, 0.1),
      });
    }
    return Buffer.from(await doc.save());
  }

  // ── Evidence ──────────────────────────────────────────────

  private async dataUri(att: Attachment): Promise<string | null> {
    // The renderer is Chromium, which cannot draw HEIC: named, not a broken image.
    if (!att.mimeType.startsWith('image/') || /^image\/hei[cf]/.test(att.mimeType)) return null;
    try {
      const buf = await this.storage.read(att.storageKey);
      return `data:${att.mimeType};base64,${buf.toString('base64')}`;
    } catch {
      return null; // a missing file must not sink the whole document
    }
  }

  /** A file as a figure on an evidence page. An image is drawn in. A PDF is
   *  named and queued so its own pages follow the document — that is the
   *  attachment itself, not a second copy of the record. A debit note passes
   *  `listed`: a photo and a PDF are both named on the one supporting page, the
   *  photo is drawn there, and the PDF's pages still follow. Anything else is
   *  named only. */
  private async figureOf(file: Attachment, caption: string, appendPdfs: Attachment[], documentNoun: string, listed = false): Promise<string> {
    const uri = await this.dataUri(file);
    const appended = file.mimeType === 'application/pdf';
    if (appended) appendPdfs.push(file);
    if (listed) {
      // The tenant sees the description and, for a photo, the picture. The
      // office's filename stays off the note.
      const image = uri ? `<img src="${uri}" alt="">` : '';
      return `<figure>${image}${caption ? `<figcaption>${caption}</figcaption>` : ''}</figure>`;
    }
    if (uri) return `<figure><img src="${uri}" alt=""><figcaption>${caption}</figcaption></figure>`;
    return `<figure><div class="file">${esc(file.filename)}${appended ? ` — its pages follow at the end of this ${documentNoun}` : ''}</div><figcaption>${caption}</figcaption></figure>`;
  }

  /** Dial photos for the readings this note billed, then — on one page — the
   *  files attached to its charges or to the note, and the notices of a change
   *  of standard charge it is the first to bill. Photos and PDFs are both
   *  named on that page; a PDF's own pages follow, so the attachment is still
   *  in the note. */
  private async evidencePages(organizationId: string, invoiceId: string, ctx: InvoiceDocumentContext): Promise<{ html: string; appendPdfs: Attachment[] }> {
    const pages: string[] = [];
    const appendPdfs: Attachment[] = [];

    const readingIds = [...new Set(ctx.lines.map((l) => l.meter?.meterReadingId).filter((v): v is string => typeof v === 'string'))];
    if (readingIds.length > 0) {
      const readings = await this.prisma.meterReading.findMany({
        where: { id: { in: readingIds } },
        include: { meter: { include: { units: { include: { unit: { select: { name: true } } } } } } },
      });
      const shots = await this.prisma.attachment.findMany({
        where: { organizationId, ownerType: 'METER_READING', ownerId: { in: readingIds } },
        orderBy: { createdAt: 'asc' },
      });
      const uris = new Map<string, string | null>();
      for (const s of shots) uris.set(s.id, await this.dataUri(s));

      const blocks: string[] = [];
      for (const r of readings) {
        const mine = shots.filter((s) => s.ownerId === r.id);
        const pick = (role: string) => mine.find((s) => s.role === role) ?? null;
        const start = pick('START');
        const end = pick('END');
        if (!start && !end) continue; // nothing to evidence
        const usage = new Decimal(r.readingEnd.toString()).minus(r.readingStart.toString());
        const shot = (label: string, when: Date, value: string, att: Attachment | null) =>
          `<div class="shot"><div class="lbl">${label}</div>` +
          `<div>${ddmmyyyy(when)} <span class="val">${esc(value)}</span></div>` +
          (att && uris.get(att.id) ? `<img src="${uris.get(att.id)}" alt="">` : '') +
          `</div>`;
        blocks.push(
          `<div class="meter">` +
            `<div class="meter-head"><b>${esc(r.meter.units.map((u) => u.unit.name).join(', '))}</b>` +
            `<span>${r.meter.serialNo ? `(No.${esc(r.meter.serialNo)})` : ''}</span></div>` +
            `<div class="shots">` +
              shot('Start', r.periodStart, r.readingStart.toString(), start) +
              shot('End', r.periodEnd, r.readingEnd.toString(), end) +
              `<div class="shot"><div class="lbl">Usage</div><div><span class="val">${usage.toString()}</span></div></div>` +
            `</div></div>`,
        );
      }
      if (blocks.length) {
        pages.push(`<section class="page ev"><h2>Meter readings — ${esc(ctx.doc.number)}</h2>${blocks.join('')}</section>`);
      }
    }

    // Files on the charges or on the note, then the management company's notice
    // of a new fee — the note that first bills it, so the tenant sees why this
    // month's fee is not last month's. One page names all of them. A photo is
    // drawn there; a PDF's own pages follow the note.
    const lineIds = ctx.lines.map((l) => l.id);
    const docs = await this.prisma.attachment.findMany({
      where: {
        organizationId,
        OR: [
          { ownerType: 'INVOICE_LINE', ownerId: { in: lineIds.length ? lineIds : ['-'] } },
          { ownerType: 'INVOICE', ownerId: invoiceId },
        ],
      },
      orderBy: { createdAt: 'asc' },
    });
    const labelFor = new Map(ctx.lines.map((l) => [l.id, l.description]));
    const supporting: string[] = [];
    for (const d of docs) {
      const label = labelFor.get(d.ownerId);
      const charge = label ? printedParticulars(label) : '';
      // A caption the office typed is a description. The filename is not, and
      // neither is a caption that is just the filename.
      const described = d.caption && d.caption !== d.filename ? d.caption : '';
      const caption = esc(charge || described);
      supporting.push(await this.figureOf(d, caption, appendPdfs, 'note', true));
    }

    const changed = [...new Set(ctx.lines.flatMap((l) => l.standardChanged))];
    const noticeFigures: string[] = [];
    if (changed.length > 0) {
      const notices = await this.prisma.propertyNotice.findMany({
        where: { organizationId, standardChargeId: { in: changed } },
        orderBy: { date: 'asc' },
        include: { standardCharge: { select: { chargeType: { select: { nameEn: true } } } } },
      });
      const files = notices.length
        ? await this.prisma.attachment.findMany({
            where: { organizationId, ownerType: 'PROPERTY_NOTICE', ownerId: { in: notices.map((n) => n.id) } },
            orderBy: { createdAt: 'asc' },
          })
        : [];
      for (const n of notices) {
        // The letter's own date and the file name are the office's record.
        // The tenant's note names the charge only; the letter itself follows.
        const caption = esc(n.standardCharge?.chargeType.nameEn ?? '');
        for (const file of files.filter((x) => x.ownerId === n.id)) {
          noticeFigures.push(await this.figureOf(file, caption, appendPdfs, 'note', true));
        }
      }
    }

    const blocks = [
      supporting.length ? `<h2>Supporting documents — ${esc(ctx.doc.number)}</h2><div class="docs">${supporting.join('')}</div>` : '',
      noticeFigures.length ? `<h2>Notice of change — ${esc(ctx.doc.number)}</h2><div class="docs">${noticeFigures.join('')}</div>` : '',
    ].filter(Boolean);
    if (blocks.length) pages.push(`<section class="page ev">${blocks.join('')}</section>`);

    return { html: pages.join(''), appendPdfs };
  }
}
