import { Injectable } from '@nestjs/common';
import type { Currency, Prisma } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { hkIsoDay, hkToday, parseDay } from '../common/hk-date';
import { findSystemAccount } from '../ledger/system-accounts';
import { heldByDeposit } from '../deposits/deposit-held';
import { creditByLease } from '../payments/lease-credit';
import { addressOf, buildingOf, premisesLines, propertiesOf } from '../common/lease-premises';
import { loadUnitHistories } from '../standard-charges/standard-charge.service';
import { followedFigureOn } from '../standard-charges/standard-billing';
import { PrismaService } from '../prisma/prisma.service';
import type {
  ArAging,
  ArAgingBuckets,
  ArAgingGroup,
  Bilingual,
  Collections,
  CollectionsGroup,
  Dashboard,
  DashboardMoney,
  DashboardRate,
  IncomeStatement,
  IncomeStatementGroup,
  IncomeStatementLine,
  OutstandingInvoiceQuery,
  OutstandingInvoices,
  RentRoll,
  RentRollGroup,
  Settlement,
  Statement,
  StatementQuery,
  StatementRow,
  Statements,
  TrialBalance,
  TrialBalanceGroup,
  TrialBalanceRow,
} from './reports.types';

// Day boundaries in Hong Kong local time (UTC+8) — the business calendar — so a
// transaction posted at, say, 07:00 HKT is attributed to the correct local day,
// not the UTC day. (Could be promoted to a per-org timezone setting.)
const startOfDay = (s: string) => new Date(`${s}T00:00:00.000+08:00`);
const endOfDay = (s: string) => new Date(`${s}T23:59:59.999+08:00`);

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/** "2026-10" as a tenant reads it: "Oct 2026". */
const periodLabel = (period: string) => {
  const [y, m] = period.split('-').map(Number);
  return MONTHS[m - 1] ? `${MONTHS[m - 1]} ${y}` : period;
};
/** Whole days from one "YYYY-MM-DD" to another. */
const daysBetween = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);

// Stable display order; unknown currencies sort last, then alphabetically.
const CURRENCY_ORDER: Currency[] = ['HKD', 'SGD'];
const orderCurrencies = (curs: Iterable<Currency>): Currency[] =>
  [...new Set(curs)].sort((a, b) => {
    const ia = CURRENCY_ORDER.indexOf(a), ib = CURRENCY_ORDER.indexOf(b);
    return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib) || a.localeCompare(b);
  });

/**
 * Read-only financial reports, all derived from the append-only double-entry
 * ledger (journal lines) — never from stored balances. Everything is grouped by
 * currency: there is no FX, so each currency's books balance on their own and are
 * never summed together. The per-currency trial balance proves Σ debits == Σ credits.
 */
@Injectable()
export class ReportsService {
  constructor(private readonly prisma: PrismaService) {}

  /** Every account's net position as of a date, per currency. Total debits must
   * equal total credits within each currency. */
  async trialBalance(organizationId: string, asOf: string): Promise<TrialBalance> {
    const nets = await this.netByAccount({ account: { organizationId }, entry: { entryDate: { lte: endOfDay(asOf) } } });
    const byCur = new Map<Currency, { rows: TrialBalanceRow[]; totalDebit: Decimal; totalCredit: Decimal }>();
    for (const { account: acc, net, currency: cur } of nets) {
      const debit = net.gt(0) ? net : new Decimal(0);
      const credit = net.lt(0) ? net.abs() : new Decimal(0);
      const g = byCur.get(cur) ?? { rows: [], totalDebit: new Decimal(0), totalCredit: new Decimal(0) };
      g.rows.push({ code: acc.code, name: acc.name, type: acc.type, debit: debit.toFixed(2), credit: credit.toFixed(2) });
      g.totalDebit = g.totalDebit.plus(debit);
      g.totalCredit = g.totalCredit.plus(credit);
      byCur.set(cur, g);
    }
    const groups: TrialBalanceGroup[] = orderCurrencies(byCur.keys()).map((currency) => {
      const g = byCur.get(currency)!;
      return {
        currency,
        rows: g.rows,
        totalDebit: g.totalDebit.toFixed(2),
        totalCredit: g.totalCredit.toFixed(2),
        balanced: g.totalDebit.equals(g.totalCredit),
      };
    });
    return { asOf, groups };
  }

  /** Each account's net (debits − credits) per currency over the lines matched,
   *  dropping the ones at zero, in account-code order. One grouped read: the
   *  chart is the office's whole ERP chart, thousands of accounts, nearly all
   *  never posted to here. An account with a balance is reported whether or
   *  not it is still active — leaving a retired one out would unbalance the
   *  trial balance. */
  private async netByAccount(where: Prisma.JournalLineWhereInput) {
    const sums = await this.prisma.journalLine.groupBy({
      by: ['accountId', 'currency', 'direction'],
      where,
      _sum: { amount: true },
    });
    const accounts = await this.prisma.glAccount.findMany({
      where: { id: { in: [...new Set(sums.map((s) => s.accountId))] } },
      orderBy: { code: 'asc' },
    });
    const net = new Map<string, Decimal>();
    for (const s of sums) {
      const key = `${s.accountId} ${s.currency}`;
      const amount = new Decimal((s._sum.amount ?? 0).toString());
      net.set(key, (net.get(key) ?? new Decimal(0)).plus(s.direction === 'DEBIT' ? amount : amount.negated()));
    }
    const out: { account: (typeof accounts)[number]; currency: Currency; net: Decimal }[] = [];
    for (const account of accounts) {
      for (const currency of orderCurrencies(new Set(sums.filter((s) => s.accountId === account.id).map((s) => s.currency)))) {
        const n = net.get(`${account.id} ${currency}`)!;
        if (!n.isZero()) out.push({ account, currency, net: n });
      }
    }
    return out;
  }

  /** Outstanding receivables per lease, aged by each invoice's due date, per
   *  currency. Given tenants, only theirs; the tenants to pick from are everyone
   *  owing at the date either way. A tenant's leases sit together, the tenant
   *  owing most first. */
  async arAging(organizationId: string, asOf: string, tenantIds: readonly string[] = []): Promise<ArAging> {
    const upTo = endOfDay(asOf);
    const parts = await this.arByInvoice(organizationId, upTo);
    const owedIds = [...parts].filter(([, p]) => p.outstanding.gt(0)).map(([id]) => id);
    if (owedIds.length === 0) return { asOf, tenants: [], groups: [] };

    const invoices = await this.prisma.invoice.findMany({
      where: { id: { in: owedIds } },
      select: {
        id: true,
        dueDate: true,
        currency: true,
        lease: {
          select: {
            id: true,
            reference: true,
            tenant: { select: { id: true, name: true } },
            units: { select: { unit: { select: { name: true, property: { select: { id: true, name: true, address: true } } } } } },
          },
        },
      },
    });
    const tenants = [...new Map(invoices.map((inv) => [inv.lease.tenant.id, inv.lease.tenant])).values()].sort((a, b) =>
      a.name.localeCompare(b.name),
    );
    const shown = tenantIds.length ? invoices.filter((inv) => tenantIds.includes(inv.lease.tenant.id)) : invoices;

    const asOfMs = upTo.getTime();
    type Lease = (typeof invoices)[number]['lease'];
    type Grp = { perLease: Map<string, { lease: Lease; b: ReturnType<typeof zeroBuckets> }>; totals: ReturnType<typeof zeroBuckets> };
    const byCur = new Map<Currency, Grp>();
    for (const inv of shown) {
      const amt = parts.get(inv.id)!.outstanding;
      const ageDays = Math.floor((asOfMs - inv.dueDate.getTime()) / 86_400_000);
      const key = ageDays <= 0 ? 'current' : ageDays <= 30 ? 'd1_30' : ageDays <= 60 ? 'd31_60' : ageDays <= 90 ? 'd61_90' : 'd90plus';
      const grp = byCur.get(inv.currency) ?? { perLease: new Map(), totals: zeroBuckets() };
      const row = grp.perLease.get(inv.lease.id) ?? { lease: inv.lease, b: zeroBuckets() };
      row.b[key] = row.b[key].plus(amt);
      row.b.total = row.b.total.plus(amt);
      grp.perLease.set(inv.lease.id, row);
      grp.totals[key] = grp.totals[key].plus(amt);
      grp.totals.total = grp.totals.total.plus(amt);
      byCur.set(inv.currency, grp);
    }
    const groups: ArAgingGroup[] = orderCurrencies(byCur.keys()).map((currency) => {
      const g = byCur.get(currency)!;
      const lines = [...g.perLease.values()];
      const owedBy = new Map<string, Decimal>();
      for (const l of lines) owedBy.set(l.lease.tenant.id, (owedBy.get(l.lease.tenant.id) ?? new Decimal(0)).plus(l.b.total));
      const rows = lines
        .sort(
          (a, b) =>
            owedBy.get(b.lease.tenant.id)!.minus(owedBy.get(a.lease.tenant.id)!).toNumber() ||
            a.lease.tenant.name.localeCompare(b.lease.tenant.name) ||
            a.lease.tenant.id.localeCompare(b.lease.tenant.id) ||
            b.b.total.minus(a.b.total).toNumber(),
        )
        .map(({ lease, b }) => {
          const props = propertiesOf(lease.units);
          return {
            tenantId: lease.tenant.id,
            tenantName: lease.tenant.name,
            leaseId: lease.id,
            leaseReference: lease.reference,
            premises: premisesLines(lease.units.map((u) => u.unit.name), buildingOf(props), addressOf(props)).join(', '),
            ...bucketsToStrings(b),
          };
        });
      return { currency, rows, totals: bucketsToStrings(g.totals) };
    });
    return { asOf, tenants, groups };
  }

  /** Every debit note as at a date, one row each, with every field the office
   *  can lay the report out from. The notes are the ones the ledger has on the
   *  receivable account by then — the same as AR Aging reads — plus, when asked,
   *  the ones not issued yet. */
  async outstandingInvoices(organizationId: string, q: OutstandingInvoiceQuery): Promise<OutstandingInvoices> {
    const upTo = endOfDay(q.asOf);
    const parts = await this.arByInvoice(organizationId, upTo);

    // A note not issued yet has posted nothing of its own, so its face value
    // stands as owed. Its b/f lines are left out: carrying a balance onto it
    // already posted, and arByInvoice has that.
    if (q.includeUnissued) {
      const unissued = await this.prisma.invoice.findMany({
        where: { organizationId, status: { in: ['DRAFT', 'PENDING_APPROVAL', 'APPROVED'] }, createdAt: { lte: upTo } },
        select: { id: true, lines: { where: { kind: { not: 'OVERDUE_CARRYFORWARD' } }, select: { amount: true } } },
      });
      for (const inv of unissued) {
        const face = sum(inv.lines.map((l) => l.amount.toString()));
        const p = parts.get(inv.id) ?? zeroParts();
        p.invoiceAmount = p.invoiceAmount.plus(face);
        p.outstanding = p.outstanding.plus(face);
        parts.set(inv.id, p);
      }
    }

    const wanted = new Set(q.settlement);
    const settlementOf = new Map<string, Settlement>();
    for (const [id, p] of parts) {
      // Nothing charged and nothing moved by the date: a note voided before it.
      if (Object.values(p).every((v) => v.isZero())) continue;
      const owed = p.invoiceAmount.plus(p.broughtForward);
      const s: Settlement = p.outstanding.lte(0) ? 'SETTLED' : p.outstanding.gte(owed) ? 'UNSETTLED' : 'PARTIAL';
      if (wanted.has(s)) settlementOf.set(id, s);
    }
    if (settlementOf.size === 0) return { asOf: q.asOf, rows: [] };

    const range = <T>(from: T | undefined, to: T | undefined) => (from || to ? { gte: from, lte: to } : undefined);
    const invoices = await this.prisma.invoice.findMany({
      where: {
        id: { in: [...settlementOf.keys()] },
        // issueDate is a moment, so its bounds are Hong Kong day boundaries;
        // dueDate is a calendar day, stored as UTC midnight.
        issueDate: range(q.issueFrom ? startOfDay(q.issueFrom) : undefined, q.issueTo ? endOfDay(q.issueTo) : undefined),
        dueDate: range(q.dueFrom ? parseDay(q.dueFrom) : undefined, q.dueTo ? parseDay(q.dueTo) : undefined),
        billingPeriod: range(q.periodFrom, q.periodTo),
      },
      orderBy: [{ dueDate: 'asc' }, { number: 'asc' }],
      select: {
        id: true,
        number: true,
        status: true,
        currency: true,
        billingPeriod: true,
        issueDate: true,
        dueDate: true,
        note: true,
        unitScope: true,
        bankAccount: { select: { name: true } },
        lines: { where: { kind: 'CHARGE' }, orderBy: { sortOrder: 'asc' }, select: { chargeType: { select: { id: true, nameEn: true, nameZh: true } } } },
        lease: {
          select: {
            reference: true,
            status: true,
            startDate: true,
            endDate: true,
            leaseTypeId: true,
            usageId: true,
            tenant: {
              select: {
                name: true,
                nameZh: true,
                attention: true,
                phone: true,
                email: true,
                codes: { select: { landlordId: true, code: true, glAccount: { select: { code: true } } } },
              },
            },
            units: {
              select: {
                unitId: true,
                unit: {
                  select: {
                    name: true,
                    property: {
                      select: {
                        id: true,
                        name: true,
                        code: true,
                        address: true,
                        regionId: true,
                        categoryId: true,
                        landlord: { select: { id: true, code: true, name: true, nameZh: true } },
                      },
                    },
                  },
                },
              },
            },
            labels: { select: { label: { select: { name: true } } } },
          },
        },
      },
    });

    // The option lists the lease and its properties point into.
    const named = await this.referenceNamer(
      invoices.flatMap((inv) => [
        inv.lease.leaseTypeId,
        inv.lease.usageId,
        ...inv.lease.units.flatMap((u) => [u.unit.property.regionId, u.unit.property.categoryId]),
      ]),
    );

    const rows = invoices.map((inv) => {
      const p = parts.get(inv.id)!;
      const { lease } = inv;
      // A split note bills only the units in its scope.
      const scope = Array.isArray(inv.unitScope) ? (inv.unitScope as string[]) : null;
      const scoped = scope ? lease.units.filter((u) => scope.includes(u.unitId)) : [];
      const units = scoped.length ? scoped : lease.units;
      const props = propertiesOf(units);
      const landlord = props.find((pr) => pr.landlord)?.landlord ?? null;
      const code = landlord ? lease.tenant.codes.find((c) => c.landlordId === landlord.id) : undefined;
      const chargeTypes = new Map<string, Bilingual>();
      for (const l of inv.lines) if (l.chargeType) chargeTypes.set(l.chargeType.id, { en: l.chargeType.nameEn, zh: l.chargeType.nameZh });
      return {
        id: inv.id,
        number: inv.number,
        status: inv.status,
        settlement: settlementOf.get(inv.id)!,
        currency: inv.currency,
        billingPeriod: inv.billingPeriod,
        issueDate: inv.issueDate ? hkIsoDay(inv.issueDate) : null,
        dueDate: hkIsoDay(inv.dueDate),
        bankAccount: inv.bankAccount?.name ?? null,
        chargeTypes: [...chargeTypes.values()],
        units: units.map((u) => u.unit.name).join(', '),
        note: inv.note,

        invoiceAmount: p.invoiceAmount.toFixed(2),
        broughtForward: p.broughtForward.toFixed(2),
        received: p.received.toFixed(2),
        depositApplied: p.depositApplied.toFixed(2),
        carriedForward: p.carriedForward.toFixed(2),
        outstanding: p.outstanding.toFixed(2),

        tenantCode: code?.code ?? null,
        tenantName: lease.tenant.name,
        tenantNameZh: lease.tenant.nameZh,
        attention: lease.tenant.attention,
        phone: lease.tenant.phone,
        email: lease.tenant.email,
        arAccount: code?.glAccount?.code ?? null,

        leaseReference: lease.reference,
        leaseStatus: lease.status,
        leaseStart: hkIsoDay(lease.startDate),
        leaseEnd: hkIsoDay(lease.endDate),
        leaseType: named([lease.leaseTypeId]),
        leaseUsage: named([lease.usageId]),
        leaseLabels: lease.labels.map((l) => l.label.name),

        building: buildingOf(props),
        propertyCodes: [...new Set(props.map((pr) => pr.code).filter((c) => c))].join(', '),
        address: addressOf(props),
        region: named(props.map((pr) => pr.regionId)),
        category: named(props.map((pr) => pr.categoryId)),

        landlordCode: landlord?.code ?? null,
        landlordName: landlord?.name ?? null,
        landlordNameZh: landlord?.nameZh ?? null,
      };
    });
    return { asOf: q.asOf, rows };
  }

  /** Each lease's statement for a period — the tenant's account as the ERP's
   *  monthly statement prints it: what was owed at the start, every document
   *  that moved the lease's receivable since (debit notes, payments, deposit
   *  and credit used, voids, bounces) with the balance running down, then what
   *  is owed at the end by age, and the deposit and unused credit held. All
   *  from the ledger — the same lines AR Aging reads, so the closing balances
   *  add up to it.
   *
   *  A carry-forward is left out: it moves a balance from one of the lease's
   *  notes to another, and the tenant owes the same either side of it.
   *
   *  Returns every lease with anything to print, and every active lease. */
  async statements(organizationId: string, q: StatementQuery): Promise<Statements> {
    const fromStart = startOfDay(q.from);
    const upTo = endOfDay(q.to);

    const leases = await this.prisma.lease.findMany({
      where: { organizationId, deletedAt: null, ...(q.leaseIds ? { id: { in: q.leaseIds } } : {}) },
      orderBy: { reference: 'asc' },
      select: {
        id: true,
        reference: true,
        status: true,
        currency: true,
        tenantId: true,
        tenant: {
          select: { name: true, nameZh: true, attention: true, phone: true, email: true, codes: { select: { landlordId: true, code: true } } },
        },
        units: {
          select: {
            unit: {
              select: {
                name: true,
                property: { select: { id: true, name: true, address: true, regionId: true, landlord: { select: { id: true, code: true, name: true } } } },
              },
            },
          },
        },
        invoices: { select: { id: true, number: true, issueDate: true, dueDate: true, billingPeriod: true } },
        deposits: { select: { id: true, sourceInvoiceId: true } },
      },
    });
    if (leases.length === 0) return { from: q.from, to: q.to, statements: [] };

    const invoiceOf = new Map(leases.flatMap((l) => l.invoices.map((i) => [i.id, { ...i, leaseId: l.id }] as const)));
    const ar = await findSystemAccount(this.prisma, organizationId, 'RECEIVABLE');
    const lines = ar
      ? await this.prisma.journalLine.findMany({
          where: {
            accountId: ar.id,
            invoiceId: q.leaseIds ? { in: [...invoiceOf.keys()] } : { not: null },
            entry: { entryDate: { lte: upTo } },
          },
          select: {
            id: true,
            invoiceId: true,
            direction: true,
            amount: true,
            entry: { select: { id: true, entryDate: true, createdAt: true, sourceType: true, sourceId: true, memo: true, reverses: { select: { sourceType: true } } } },
          },
        })
      : [];
    const signed = (l: (typeof lines)[number]) => (l.direction === 'DEBIT' ? new Decimal(l.amount.toString()) : new Decimal(l.amount.toString()).negated());
    const sourceOf = (l: (typeof lines)[number]) => l.entry.reverses?.sourceType ?? l.entry.sourceType;
    const inPeriod = lines.filter((l) => l.entry.entryDate >= fromStart && sourceOf(l) !== 'ADJUSTMENT');

    // The documents behind the period's lines, for their numbers and amounts.
    const idsOf = (...types: string[]) => [...new Set(inPeriod.filter((l) => types.includes(sourceOf(l))).map((l) => l.entry.sourceId))];
    const [chargeLines, receipts, drawings, deposits, held, credit] = await Promise.all([
      this.prisma.invoiceLine.findMany({
        where: { invoiceId: { in: idsOf('INVOICE', 'OPENING_BALANCE') }, kind: 'CHARGE' },
        orderBy: { sortOrder: 'asc' },
        select: { invoiceId: true, chargeType: { select: { nameEn: true } } },
      }),
      this.prisma.receipt.findMany({
        where: { id: { in: idsOf('RECEIPT') } },
        select: { id: true, number: true, amount: true, reference: true, settlementMethod: { select: { nameEn: true } } },
      }),
      this.prisma.receiptAllocation.findMany({
        where: { id: { in: idsOf('RECEIPT_ALLOCATION') } },
        select: { id: true, receipt: { select: { number: true, amount: true } } },
      }),
      this.prisma.deposit.findMany({ where: { id: { in: idsOf('DEPOSIT_ALLOCATION') } }, select: { id: true, number: true } }),
      heldByDeposit(this.prisma, organizationId, leases.flatMap((l) => l.deposits), upTo),
      creditByLease(this.prisma, organizationId, leases.map((l) => l.id), upTo),
    ]);
    const chargesOf = new Map<string, string[]>();
    for (const c of chargeLines) {
      const names = chargesOf.get(c.invoiceId) ?? [];
      if (c.chargeType && !names.includes(c.chargeType.nameEn)) names.push(c.chargeType.nameEn);
      chargesOf.set(c.invoiceId, names);
    }
    const receiptOf = new Map(receipts.map((r) => [r.id, r]));
    const drawingOf = new Map(drawings.map((d) => [d.id, d]));
    const depositOf = new Map(deposits.map((d) => [d.id, d]));

    const named = await this.referenceNamer(leases.flatMap((l) => l.units.map((u) => u.unit.property.regionId)));

    /** How a group of lines — one document, or its part on one note — reads. */
    const describe = (group: typeof lines, net: Decimal): Pick<StatementRow, 'kind' | 'number' | 'description' | 'amount'> => {
      const { entry, invoiceId } = group[0];
      const reversal = !!entry.reverses;
      const inv = invoiceOf.get(invoiceId!)!;
      const moved = net.abs().toFixed(2);
      switch (sourceOf(group[0])) {
        case 'INVOICE':
        case 'OPENING_BALANCE': {
          if (reversal) return { kind: 'VOID', number: inv.number ?? '', description: 'Debit note voided', amount: moved };
          const what = entry.sourceType === 'OPENING_BALANCE' ? 'Opening balance' : (chargesOf.get(inv.id) ?? []).join(', ') || 'Debit note';
          return { kind: 'INVOICE', number: inv.number ?? '', description: `${periodLabel(inv.billingPeriod)} — ${what}`, amount: moved };
        }
        case 'RECEIPT': {
          const r = receiptOf.get(entry.sourceId);
          const how = [r?.settlementMethod?.nameEn, r?.reference].filter(Boolean).join(' ');
          return reversal
            ? { kind: 'REVERSAL', number: r?.number ?? '', description: 'Payment returned unpaid', amount: r ? r.amount.toFixed(2) : moved }
            : { kind: 'PAYMENT', number: r?.number ?? '', description: how ? `Payment — ${how}` : 'Payment', amount: r ? r.amount.toFixed(2) : moved };
        }
        case 'RECEIPT_ALLOCATION': {
          const d = drawingOf.get(entry.sourceId);
          return reversal
            ? { kind: 'REVERSAL', number: d?.receipt.number ?? '', description: 'Advance payment taken back', amount: moved }
            : { kind: 'CREDIT_APPLIED', number: d?.receipt.number ?? '', description: 'Advance payment applied', amount: d ? d.receipt.amount.toFixed(2) : moved };
        }
        case 'DEPOSIT_ALLOCATION': {
          // Undoing an application posts back the other way rather than as a reversal.
          const undone = reversal || net.gt(0);
          return { kind: 'DEPOSIT_APPLIED', number: depositOf.get(entry.sourceId)?.number ?? '', description: undone ? 'Deposit application undone' : 'Deposit applied', amount: moved };
        }
        default:
          return { kind: 'OTHER', number: inv.number ?? '', description: entry.memo ?? entry.sourceType, amount: moved };
      }
    };

    const linesOf = new Map<string, typeof lines>();
    for (const l of lines) {
      const leaseId = invoiceOf.get(l.invoiceId!)?.leaseId;
      if (!leaseId) continue;
      const list = linesOf.get(leaseId);
      if (list) list.push(l);
      else linesOf.set(leaseId, [l]);
    }
    const order = (a: (typeof lines)[number], b: (typeof lines)[number]) =>
      a.entry.entryDate.getTime() - b.entry.entryDate.getTime() || a.entry.createdAt.getTime() - b.entry.createdAt.getTime() || a.entry.id.localeCompare(b.entry.id);
    const dayBefore = hkIsoDay(new Date(fromStart.getTime() - 1));

    const statements: Statement[] = [];
    for (const lease of leases) {
      const mine = (linesOf.get(lease.id) ?? []).sort(order);
      const owedAt = (until: Date) => {
        const by = new Map<string, Decimal>();
        for (const l of mine) if (l.entry.entryDate <= until) by.set(l.invoiceId!, (by.get(l.invoiceId!) ?? new Decimal(0)).plus(signed(l)));
        return by;
      };
      const openingByNote = owedAt(new Date(fromStart.getTime() - 1));
      const opening = sum([...openingByNote.values()].map((v) => v.toString()));

      const rows: StatementRow[] = [];
      let balance = new Decimal(0);
      const push = (r: Omit<StatementRow, 'debit' | 'credit' | 'balance'>, net: Decimal) => {
        balance = balance.plus(net);
        rows.push({ ...r, debit: net.gt(0) ? net.toFixed(2) : null, credit: net.lt(0) ? net.abs().toFixed(2) : null, balance: balance.toFixed(2) });
      };
      if (q.openingItems) {
        const owing = [...openingByNote].filter(([, v]) => !v.isZero()).map(([id, v]) => ({ inv: invoiceOf.get(id)!, v }));
        owing.sort((a, b) => a.inv.dueDate.getTime() - b.inv.dueDate.getTime() || (a.inv.number ?? '').localeCompare(b.inv.number ?? ''));
        for (const { inv, v } of owing) {
          push(
            {
              kind: 'OPENING_ITEM',
              date: inv.issueDate ? hkIsoDay(inv.issueDate) : null,
              number: inv.number ?? '',
              description: `${periodLabel(inv.billingPeriod)} — balance b/f`,
              amount: null,
            },
            v,
          );
        }
      } else {
        balance = opening;
        rows.push({ kind: 'BALANCE_BF', date: dayBefore, number: '', description: 'Balance brought forward', amount: null, debit: null, credit: null, balance: opening.toFixed(2) });
      }

      // One row per document, or per note it moved; in the order they posted.
      const groups = new Map<string, typeof lines>();
      for (const l of mine) {
        if (l.entry.entryDate < fromStart || sourceOf(l) === 'ADJUSTMENT') continue;
        const key = q.groupEntries ? l.entry.id : `${l.entry.id}:${l.invoiceId}`;
        const group = groups.get(key);
        if (group) group.push(l);
        else groups.set(key, [l]);
      }
      let debit = new Decimal(0);
      let creditTotal = new Decimal(0);
      for (const group of groups.values()) {
        const net = sum(group.map((l) => signed(l).toString()));
        if (net.isZero()) continue;
        const d = describe(group, net);
        // A part of a document names the note it went to, unless it is the note.
        const onNote = !q.groupEntries && d.kind !== 'INVOICE' && d.kind !== 'VOID' ? invoiceOf.get(group[0].invoiceId!)?.number : null;
        push({ ...d, date: hkIsoDay(group[0].entry.entryDate), description: onNote ? `${d.description} (${onNote})` : d.description }, net);
        if (net.gt(0)) debit = debit.plus(net);
        else creditTotal = creditTotal.plus(net.abs());
      }

      // What is owed at the end, by age: not yet due, then days past due — or
      // since issue — in the ERP's buckets.
      const aging = { notYetDue: new Decimal(0), d0_30: new Decimal(0), d31_60: new Decimal(0), d61_90: new Decimal(0), over90: new Decimal(0) };
      for (const [id, v] of owedAt(upTo)) {
        if (v.isZero()) continue;
        const inv = invoiceOf.get(id)!;
        const due = hkIsoDay(inv.dueDate);
        const since = q.agingBasis === 'issue' && inv.issueDate ? hkIsoDay(inv.issueDate) : due;
        const age = daysBetween(since, q.to);
        const key = daysBetween(due, q.to) <= 0 ? 'notYetDue' : age <= 30 ? 'd0_30' : age <= 60 ? 'd31_60' : age <= 90 ? 'd61_90' : 'over90';
        aging[key] = aging[key].plus(v);
      }

      const closing = opening.plus(debit).minus(creditTotal);
      const deposit = sum(lease.deposits.map((d) => (held.get(d.id) ?? new Decimal(0)).toString()));
      const unallocated = credit.get(lease.id) ?? new Decimal(0);
      const active = !opening.isZero() || groups.size > 0 || !closing.isZero() || !deposit.isZero() || !unallocated.isZero();
      if (!active && lease.status !== 'ACTIVE') continue;

      const props = propertiesOf(lease.units);
      const landlord = props.find((p) => p.landlord)?.landlord ?? null;
      statements.push({
        leaseId: lease.id,
        leaseReference: lease.reference,
        leaseStatus: lease.status,
        currency: lease.currency,
        tenantId: lease.tenantId,
        tenantName: lease.tenant.name,
        tenantNameZh: lease.tenant.nameZh,
        tenantCode: (landlord && lease.tenant.codes.find((c) => c.landlordId === landlord.id)?.code) ?? null,
        attention: lease.tenant.attention,
        phone: lease.tenant.phone,
        email: lease.tenant.email,
        landlordCode: landlord?.code ?? null,
        landlordName: landlord?.name ?? null,
        building: buildingOf(props),
        units: lease.units.map((u) => u.unit.name),
        address: addressOf(props),
        region: named(props.map((p) => p.regionId)),
        opening: opening.toFixed(2),
        debit: debit.toFixed(2),
        credit: creditTotal.toFixed(2),
        closing: closing.toFixed(2),
        aging: {
          notYetDue: aging.notYetDue.toFixed(2),
          d0_30: aging.d0_30.toFixed(2),
          d31_60: aging.d31_60.toFixed(2),
          d61_90: aging.d61_90.toFixed(2),
          over90: aging.over90.toFixed(2),
        },
        deposit: deposit.toFixed(2),
        unallocated: unallocated.toFixed(2),
        active,
        rows,
      });
    }
    return { from: q.from, to: q.to, statements };
  }

  /** Names reference values — lease type, usage, region, category — in both
   *  languages. The purchases of a building can differ in region or category;
   *  each is named once. */
  private async referenceNamer(ids: Iterable<string | null>): Promise<(ids: (string | null)[]) => Bilingual | null> {
    const wanted = [...new Set([...ids].filter((id): id is string => !!id))];
    const refs = new Map(
      (await this.prisma.referenceValue.findMany({ where: { id: { in: wanted } }, select: { id: true, nameEn: true, nameZh: true } })).map((r) => [r.id, r]),
    );
    return (ids) => {
      const vals = [...new Set(ids)].flatMap((id) => (id && refs.has(id) ? [refs.get(id)!] : []));
      if (vals.length === 0) return null;
      return { en: vals.map((v) => v.nameEn).join(' / '), zh: vals.some((v) => v.nameZh) ? vals.map((v) => v.nameZh ?? v.nameEn).join(' / ') : null };
    };
  }

  /** Each note's receivable as at a moment, from the ledger, split by what
   *  moved it. A reversal counts against what it reverses — a bounced receipt
   *  takes back what the receipt paid, a void takes back the charge, an unwound
   *  carry-forward takes back the transfer — so each part reads net. */
  private async arByInvoice(organizationId: string, upTo: Date): Promise<Map<string, ArParts>> {
    const out = new Map<string, ArParts>();
    const ar = await findSystemAccount(this.prisma, organizationId, 'RECEIVABLE');
    if (!ar) return out;
    const lines = await this.prisma.journalLine.findMany({
      where: { accountId: ar.id, invoiceId: { not: null }, entry: { entryDate: { lte: upTo } } },
      select: { invoiceId: true, direction: true, amount: true, entry: { select: { sourceType: true, reverses: { select: { sourceType: true } } } } },
    });
    for (const l of lines) {
      const id = l.invoiceId as string;
      const p = out.get(id) ?? zeroParts();
      const amt = new Decimal(l.amount.toString());
      p.outstanding = l.direction === 'DEBIT' ? p.outstanding.plus(amt) : p.outstanding.minus(amt);
      // A reversal's line is its original's line taken back: same side, negative.
      const reversed = l.entry.reverses;
      const source = reversed?.sourceType ?? l.entry.sourceType;
      const debit = reversed ? l.direction === 'CREDIT' : l.direction === 'DEBIT';
      const signed = reversed ? amt.negated() : amt;
      switch (source) {
        case 'INVOICE':
        case 'OPENING_BALANCE':
          p.invoiceAmount = p.invoiceAmount.plus(debit ? signed : signed.negated());
          break;
        case 'ADJUSTMENT': // a carry-forward: onto this note, or off it to a later one
          if (debit) p.broughtForward = p.broughtForward.plus(signed);
          else p.carriedForward = p.carriedForward.plus(signed);
          break;
        case 'DEPOSIT':
        case 'DEPOSIT_ALLOCATION':
        case 'DEPOSIT_REFUND':
          p.depositApplied = p.depositApplied.plus(debit ? signed.negated() : signed);
          break;
        default: // receipts, a deposit receipt's credit, anything else that pays
          p.received = p.received.plus(debit ? signed.negated() : signed);
      }
      out.set(id, p);
    }
    return out;
  }

  /** Income − expense over a period, from the ledger, per currency. */
  async incomeStatement(organizationId: string, from: string, to: string): Promise<IncomeStatement> {
    const nets = await this.netByAccount({
      account: { organizationId, type: { in: ['INCOME', 'EXPENSE'] } },
      entry: { entryDate: { gte: startOfDay(from), lte: endOfDay(to) } },
    });
    type Grp = { income: IncomeStatementLine[]; expense: IncomeStatementLine[]; totalIncome: Decimal; totalExpense: Decimal };
    const byCur = new Map<Currency, Grp>();
    for (const { account: acc, net, currency: cur } of nets) {
      const g = byCur.get(cur) ?? { income: [], expense: [], totalIncome: new Decimal(0), totalExpense: new Decimal(0) };
      byCur.set(cur, g);
      if (acc.type === 'INCOME') {
        const amt = net.negated(); // income is credit-normal
        g.income.push({ code: acc.code, name: acc.name, amount: amt.toFixed(2) });
        g.totalIncome = g.totalIncome.plus(amt);
      } else {
        g.expense.push({ code: acc.code, name: acc.name, amount: net.toFixed(2) });
        g.totalExpense = g.totalExpense.plus(net);
      }
    }
    const groups: IncomeStatementGroup[] = orderCurrencies(byCur.keys()).map((currency) => {
      const g = byCur.get(currency)!;
      return {
        currency,
        income: g.income,
        expense: g.expense,
        totalIncome: g.totalIncome.toFixed(2),
        totalExpense: g.totalExpense.toFixed(2),
        net: g.totalIncome.minus(g.totalExpense).toFixed(2),
      };
    });
    return { from, to, groups };
  }

  /** Active leases with their recurring monthly charges — expected income, per currency. */
  async rentRoll(organizationId: string): Promise<RentRoll> {
    const asOf = hkToday();
    const leases = await this.prisma.lease.findMany({
      where: { organizationId, status: 'ACTIVE', deletedAt: null },
      orderBy: { reference: 'asc' },
      include: {
        tenant: { select: { name: true } },
        units: { select: { unitId: true, unit: { select: { name: true, property: { select: { id: true, name: true } } } } } },
        // Only the rules in force today. Stepped rent is several rules on one
        // lease, each with its own window, and the engine bills whichever one
        // covers the period — summing them all reports a lease at the total of
        // every step it will ever charge.
        chargeRules: {
          where: {
            frequencyMonths: 1,
            firstInvoiceOnly: false,
            AND: [
              { OR: [{ startDate: null }, { startDate: { lte: asOf } }] },
              { OR: [{ endDate: null }, { endDate: { gte: asOf } }] },
            ],
          },
          select: { amount: true, followsStandard: true, chargeTypeId: true, unitId: true },
        },
      },
    });
    // A rule following the standard charge charges today's standard figure,
    // each unit at its own property's.
    const historyOf = await loadUnitHistories(
      this.prisma,
      organizationId,
      leases.filter((l) => l.chargeRules.some((r) => r.followsStandard)).flatMap((l) => l.units.map((u) => u.unitId)),
    );
    const monthly = (l: (typeof leases)[number], r: (typeof leases)[number]['chargeRules'][number]): string => {
      if (!r.followsStandard) return r.amount.toString();
      const units = r.unitId ? [r.unitId] : l.units.map((u) => u.unitId);
      return followedFigureOn(historyOf, r.chargeTypeId, units.length ? units : [null], asOf) ?? r.amount.toString();
    };
    const byCur = new Map<Currency, RentRollGroup>();
    for (const l of leases) {
      const g = byCur.get(l.currency) ?? { currency: l.currency, rows: [], totalMonthly: '0' };
      g.rows.push({
        reference: l.reference,
        tenantName: l.tenant.name,
        propertyName: buildingOf(propertiesOf(l.units)),
        units: l.units.map((u) => u.unit.name).join(', '),
        startDate: l.startDate,
        endDate: l.endDate,
        monthlyCharge: sum(l.chargeRules.map((r) => monthly(l, r))).toFixed(2),
      });
      byCur.set(l.currency, g);
    }
    const groups: RentRollGroup[] = orderCurrencies(byCur.keys()).map((currency) => {
      const g = byCur.get(currency)!;
      return { currency, rows: g.rows, totalMonthly: sum(g.rows.map((r) => r.monthlyCharge)).toFixed(2) };
    });
    return { groups };
  }

  /** Cash collected via receipts in a period, by settlement method, per currency —
   * derived from the append-only ledger (bank debits from RECEIPT postings, in
   * every bank account of the chart), so a closed period's figure is immutable
   * and reconciles with the trial balance. */
  async collections(organizationId: string, from: string, to: string): Promise<Collections> {
    const lines = await this.prisma.journalLine.findMany({
      where: {
        account: { organizationId, OR: [{ isBank: true }, { role: 'BANK' }] },
        direction: 'DEBIT',
        entry: { sourceType: 'RECEIPT', entryDate: { gte: startOfDay(from), lte: endOfDay(to) } },
      },
      select: { amount: true, currency: true, entry: { select: { sourceId: true } } },
    });
    if (lines.length === 0) return { from, to, groups: [] };

    const receiptIds = [...new Set(lines.map((l) => l.entry.sourceId))];
    const receipts = await this.prisma.receipt.findMany({
      where: { id: { in: receiptIds } },
      select: { id: true, settlementMethod: { select: { nameEn: true } } },
    });
    const methodOf = new Map(receipts.map((r) => [r.id, r.settlementMethod?.nameEn ?? 'Unspecified']));

    type Grp = { byMethod: Map<string, { amount: Decimal; count: number }>; total: Decimal; count: number };
    const byCur = new Map<Currency, Grp>();
    for (const l of lines) {
      const method = methodOf.get(l.entry.sourceId) ?? 'Unspecified';
      const g = byCur.get(l.currency) ?? { byMethod: new Map(), total: new Decimal(0), count: 0 };
      const cur = g.byMethod.get(method) ?? { amount: new Decimal(0), count: 0 };
      g.byMethod.set(method, { amount: cur.amount.plus(l.amount.toString()), count: cur.count + 1 });
      g.total = g.total.plus(l.amount.toString());
      g.count += 1;
      byCur.set(l.currency, g);
    }
    const groups: CollectionsGroup[] = orderCurrencies(byCur.keys()).map((currency) => {
      const g = byCur.get(currency)!;
      return {
        currency,
        methods: [...g.byMethod].map(([method, v]) => ({ method, amount: v.amount.toFixed(2), count: v.count })),
        total: g.total.toFixed(2),
        count: g.count,
      };
    });
    return { from, to, groups };
  }

  /** The four landing-page KPI tiles — same rules as the reports above: derived
   * from the ledger, never a stored balance, and grouped by currency so HKD and
   * SGD are never summed into one figure. */
  async dashboard(organizationId: string, month: string): Promise<Dashboard> {
    const [y, m] = month.split('-').map(Number);
    const from = startOfDay(`${month}-01`);
    const to = startOfDay(m === 12 ? `${y + 1}-01-01` : `${y}-${String(m + 1).padStart(2, '0')}-01`); // exclusive

    // Mirrors leases.router's displayStatus (and transitionLeases' predicate): a
    // lease whose term has passed reads as ENDED before the job flips the flag.
    const activeLeases = await this.prisma.lease.count({
      where: { organizationId, status: 'ACTIVE', deletedAt: null, endDate: { gte: new Date() } },
    });

    // Face value of the notes actually raised this month. issueDate is when the
    // note went out — it stays null for every pre-issue status, so drafts
    // exclude themselves. VOID does need excluding: voiding reverses the entry
    // but leaves the number and issue date intact.
    const invoices = await this.prisma.invoice.findMany({
      where: { organizationId, status: { not: 'VOID' }, issueDate: { gte: from, lt: to } },
      select: { currency: true, lines: { select: { amount: true } } },
    });
    const invoicedByCur = new Map<Currency, Decimal>();
    for (const inv of invoices) {
      const total = sum(inv.lines.map((l) => l.amount.toString()));
      invoicedByCur.set(inv.currency, (invoicedByCur.get(inv.currency) ?? new Decimal(0)).plus(total));
    }

    const outstandingByCur = new Map<Currency, Decimal>();
    const chargedByCur = new Map<Currency, Decimal>();
    const ar = await findSystemAccount(this.prisma, organizationId, 'RECEIVABLE');
    if (ar) {
      // Net AR per invoice, dropping the ones in credit — exactly what arAging
      // does, so this total always equals the AR Aging report's.
      const nets = await this.prisma.journalLine.groupBy({
        by: ['invoiceId', 'currency', 'direction'],
        where: { accountId: ar.id, invoiceId: { not: null } },
        _sum: { amount: true },
      });
      const perInvoice = new Map<string, { currency: Currency; net: Decimal }>();
      for (const r of nets) {
        const amt = new Decimal((r._sum.amount ?? 0).toString());
        const row = perInvoice.get(r.invoiceId as string) ?? { currency: r.currency, net: new Decimal(0) };
        row.net = r.direction === 'DEBIT' ? row.net.plus(amt) : row.net.minus(amt);
        perInvoice.set(r.invoiceId as string, row);
      }
      for (const { currency, net } of perInvoice.values()) {
        if (net.lte(0)) continue;
        outstandingByCur.set(currency, (outstandingByCur.get(currency) ?? new Decimal(0)).plus(net));
      }
      // Everything ever charged: the AR debits of the invoices' own issue
      // postings. Reversals and carry-forward transfers are other source types,
      // the same rule invoiceArState uses for its charge total.
      const charged = await this.prisma.journalLine.groupBy({
        by: ['currency'],
        where: { accountId: ar.id, direction: 'DEBIT', entry: { sourceType: 'INVOICE' } },
        _sum: { amount: true },
      });
      for (const r of charged) chargedByCur.set(r.currency, new Decimal((r._sum.amount ?? 0).toString()));
    }

    // Settled share of everything ever charged: 1 − owed/charged, per currency.
    // "Settled" is whatever is no longer owed, so a deposit applied or a credit
    // note counts, not only cash received. A currency with nothing charged is
    // 0/0 — it gets no row, and the tile shows a dash rather than claiming 0%.
    const collectionRate: DashboardRate[] = orderCurrencies(chargedByCur.keys())
      .filter((c) => chargedByCur.get(c)!.gt(0))
      .map((currency) => {
        const charged = chargedByCur.get(currency)!;
        const owed = outstandingByCur.get(currency) ?? new Decimal(0);
        return { currency, rate: charged.minus(owed).div(charged).times(100).toFixed(1) };
      });

    return {
      month,
      activeLeases,
      outstandingAr: toMoney(outstandingByCur),
      invoicedThisMonth: toMoney(invoicedByCur),
      collectionRate,
    };
  }
}

const toMoney = (byCur: Map<Currency, Decimal>): DashboardMoney[] =>
  orderCurrencies(byCur.keys()).map((currency) => ({ currency, amount: byCur.get(currency)!.toFixed(2) }));

/** A note's receivable split by what moved it; see arByInvoice. */
interface ArParts {
  invoiceAmount: Decimal;
  broughtForward: Decimal;
  received: Decimal;
  depositApplied: Decimal;
  carriedForward: Decimal;
  outstanding: Decimal;
}
const zeroParts = (): ArParts => ({
  invoiceAmount: new Decimal(0),
  broughtForward: new Decimal(0),
  received: new Decimal(0),
  depositApplied: new Decimal(0),
  carriedForward: new Decimal(0),
  outstanding: new Decimal(0),
});

function zeroBuckets() {
  return {
    current: new Decimal(0),
    d1_30: new Decimal(0),
    d31_60: new Decimal(0),
    d61_90: new Decimal(0),
    d90plus: new Decimal(0),
    total: new Decimal(0),
  };
}
function bucketsToStrings(b: ReturnType<typeof zeroBuckets>): ArAgingBuckets {
  return {
    current: b.current.toFixed(2),
    d1_30: b.d1_30.toFixed(2),
    d31_60: b.d31_60.toFixed(2),
    d61_90: b.d61_90.toFixed(2),
    d90plus: b.d90plus.toFixed(2),
    total: b.total.toFixed(2),
  };
}
