import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Prisma, type ChargeRule, type ChargeType, type Invoice, type InvoiceLine, type Lease } from '@prisma/client';
import { Decimal, sum, toCents } from '@rms/domain';
import { ApprovalService } from '../approvals/approval.service';
import { hkToday } from '../common/hk-date';
import { leaseLetterhead, letterheadPropertySelect } from '../common/letterhead';
import { propertiesOf } from '../common/lease-premises';
import { NumberService } from '../common/number.service';
import { LedgerService, type LedgerLineInput } from '../ledger/ledger.service';
import { PrismaService } from '../prisma/prisma.service';
import { loadDeductionContext, subMeterDeduction } from '../metering/sub-meter-deduction';
import { applyLeaseCredit, lockLeases } from '../payments/lease-credit';
import { findSystemAccount, systemAccount } from '../ledger/system-accounts';
import { defaultCollectionAccount } from '../ledger/bank-accounts';
import { loadTariffs, masterPropertyId, priceUsage, tariffFor } from '../metering/tariff';
import { sharePart } from '../metering/shares';
import { loadUnitHistories } from '../standard-charges/standard-charge.service';
import { followSegments, nextPeriodStart } from '../standard-charges/standard-billing';
import { heldByAnotherTenant, tenanciesForUnits } from '../metering/tenancy';
import { expandChargeRules, type EngineChargeRule } from './billing.engine';
import { deriveInvoiceStatus, invoiceArState } from './invoice-ar';
import { EDITABLE_STATUSES as EDITABLE, PRE_ISSUE_STATUSES as PRE_ISSUE } from './invoice-status';

// Chart-of-accounts code the AR control account is posted to. Seeded as "1100".
// (Could be promoted to a system setting; kept as a documented convention.)

export type InvoiceWithLines = Invoice & { lines: InvoiceLine[] };

/** Line kinds whose ledger entry is posted the moment the line is put on a
 * draft, so deleting the line would lose money that has already moved. */
const POSTED_LINE_KINDS = ['OVERDUE_CARRYFORWARD', 'DEPOSIT_APPLICATION', 'CREDIT_APPLICATION'];

/** One generated charge, before it is written to a debit note. Rule and meter
 * expansion produces CHARGE; late interest is appended as INTEREST. */
interface GeneratedLine {
  kind: 'CHARGE' | 'INTEREST';
  chargeTypeId: string | null;
  description: string;
  amount: string;
  periodStart?: Date;
  periodEnd?: Date;
  sortOrder: number;
  meta?: Prisma.InputJsonValue;
}

/** The lease shape the period expansion needs: its rules and its unit links. */
type LeaseForBilling = Lease & {
  chargeRules: (ChargeRule & { chargeType: ChargeType })[];
};

/** A metered charge plus the reading it was derived from, kept on the line's
 * `meta` so a printed debit note can show the dial photos and the arithmetic. */
interface UtilityLine {
  chargeTypeId: string;
  description: string;
  amount: string;
  periodStart: Date;
  periodEnd: Date;
  meta: Prisma.InputJsonObject;
}

/** One unit's share of a reading, billed by the note being built. */
interface ReadingClaim {
  readingId: string;
  unitId: string;
}

@Injectable()
export class BillingService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly ledger: LedgerService,
    private readonly numbers: NumberService,
    private readonly events: EventEmitter2,
    private readonly approvals: ApprovalService,
  ) {}

  /** Expands a lease's charge rules into a DRAFT invoice for the given period.
   *  No ledger posting happens here — drafts are for human review. */
  async generateDraft(input: {
    organizationId: string;
    leaseId: string;
    period: string;
    /** Split billing: bill only these units (a subset of the lease). Omit to
     * bill the whole lease. */
    unitIds?: string[];
  }): Promise<InvoiceWithLines> {
    const lease = await this.prisma.lease.findFirst({
      where: { id: input.leaseId, organizationId: input.organizationId, deletedAt: null },
      include: { chargeRules: { include: { chargeType: true } }, units: { select: { unitId: true } } },
    });
    if (!lease) throw new NotFoundException('Lease not found');
    // TERMINATED is billable so the final (part-month) note can still be raised —
    // and only up to `effectiveEnd`, since the engine clips every line's coverage
    // to the lease term, leaving nothing to bill for a later period.
    if (lease.status !== 'ACTIVE' && lease.status !== 'DRAFT' && lease.status !== 'TERMINATED') {
      throw new BadRequestException(`Cannot bill a ${lease.status} lease`);
    }
    // An early-terminated tenancy stops on terminatedAt, not on its contracted
    // endDate — that is the date the final period is prorated against.
    const effectiveEnd = lease.terminatedAt ?? lease.endDate;

    const leaseUnitIds = lease.units.map((u) => u.unitId);
    let scopeUnitIds: string[] | null = null; // null = the whole lease
    if (input.unitIds && input.unitIds.length > 0) {
      const invalid = input.unitIds.filter((id) => !leaseUnitIds.includes(id));
      if (invalid.length > 0) throw new BadRequestException('Selected units are not on this lease');
      scopeUnitIds = input.unitIds;
    }

    // "First invoice" is deterministic — the lease's starting month — not a count
    // of existing invoices (which is order-dependent and breaks on draft delete).
    const start = lease.startDate;
    const leaseStartPeriod = `${start.getUTCFullYear()}-${String(start.getUTCMonth() + 1).padStart(2, '0')}`;
    const isFirstInvoice = input.period === leaseStartPeriod;

    const { lines: lineData, readingClaims } = await this.expandPeriod({
      lease,
      leaseUnitIds,
      scopeUnitIds,
      period: input.period,
      effectiveEnd,
      isFirstInvoice,
    });

    // Late interest on this lease's overdue invoices, accrued up to now and billed
    // onto THIS debit note. Each source invoice is marked accrued so the same days
    // are never charged twice.
    const accrual = await this.accrueLateInterest(input.organizationId, lease.id, lease.interestPolicyId);
    if (accrual) {
      lineData.push({ kind: 'INTEREST', chargeTypeId: accrual.chargeTypeId, description: accrual.description, amount: accrual.amount.toFixed(2), sortOrder: 2000 });
    }

    if (lineData.length === 0) {
      throw new BadRequestException(`No charges apply for ${input.period}`);
    }

    return this.prisma.$transaction(async (tx) => {
      const invoice = await tx.invoice.create({
        data: {
          organizationId: input.organizationId,
          leaseId: lease.id,
          bankAccountId: lease.bankAccountId,
          status: 'DRAFT',
          currency: lease.currency,
          billingPeriod: input.period,
          unitScope: scopeUnitIds === null ? Prisma.DbNull : scopeUnitIds,
          dueDate: this.computeDueDate(input.period, lease.dueDayOfMonth),
          lines: { create: lineData },
        },
        include: { lines: { orderBy: { sortOrder: 'asc' } } },
      });
      if (accrual) {
        await tx.invoice.updateMany({ where: { id: { in: accrual.invoiceIds } }, data: { interestAccruedTo: accrual.now } });
      }
      await this.markReadingsBilled(tx, lineData, readingClaims, invoice.id);
      return invoice;
    });
  }

  /** Claim what a note's lines were derived from, so the next note does not
   * bill it again: each unit's share of a reading it billed (`claims`, one per
   * unit — a share that rounded to nothing included), and each planned charge. */
  private async markReadingsBilled(tx: Prisma.TransactionClient, lines: GeneratedLine[], claims: ReadingClaim[], invoiceId: string): Promise<void> {
    // The unique (reading, unit) index is the compare-and-swap. What is billable
    // was read outside this transaction, so two notes raised at once can both
    // see the same share as free; only one insert can win, and the other note
    // rolls back whole. A rebuild re-claims what it held: its own claims are
    // released first, in the same transaction.
    if (claims.length) {
      try {
        await tx.meterReadingClaim.createMany({ data: claims.map((c) => ({ ...c, invoiceId })) });
      } catch (err) {
        if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
          throw new ConflictException('A meter reading was billed by another debit note; please try again');
        }
        throw err;
      }
    }

    const claimable = { OR: [{ billedInvoiceId: null }, { billedInvoiceId: invoiceId }] };

    const plannedIds = [
      ...new Set(
        lines
          .map((l) => (l.meta && typeof l.meta === 'object' ? (l.meta as { plannedChargeId?: unknown }).plannedChargeId : undefined))
          .filter((v): v is string => typeof v === 'string'),
      ),
    ];
    if (plannedIds.length) {
      const staked = await tx.plannedCharge.updateMany({ where: { id: { in: plannedIds }, ...claimable }, data: { billedInvoiceId: invoiceId } });
      if (staked.count !== plannedIds.length) throw new ConflictException('A planned charge was billed by another debit note; please try again');
    }
  }

  /** Put a note's shares of readings back in the queue — it is being voided or
   * rebuilt, so the charges derived from them are going away and must be
   * billable again. */
  private async releaseReadings(tx: Prisma.TransactionClient, invoiceId: string): Promise<void> {
    await tx.meterReadingClaim.deleteMany({ where: { invoiceId } });
    await tx.plannedCharge.updateMany({ where: { billedInvoiceId: invoiceId }, data: { billedInvoiceId: null } });
  }

  /** Simple late interest on a lease's overdue invoices, since each invoice's
   *  grace-adjusted due date (or the point interest was last accrued), on its live
   *  outstanding. Daily rate = ratePercent / 100 / (365 annual | 30 monthly | 1 daily).
   *  Returns a single aggregated interest charge to bill on the next debit note. */
  private async accrueLateInterest(
    organizationId: string,
    leaseId: string,
    interestPolicyId: string | null,
  ): Promise<{ amount: Decimal; description: string; chargeTypeId: string; invoiceIds: string[]; now: Date } | null> {
    if (!interestPolicyId) return null;
    const policy = await this.prisma.interestPolicy.findFirst({ where: { id: interestPolicyId, organizationId, isActive: true } });
    if (!policy) return null;
    const chargeType = await this.prisma.chargeType.findFirst({ where: { organizationId, code: 'LATE_INTEREST', isActive: true }, select: { id: true } });
    if (!chargeType) return null; // no interest charge type configured → skip silently

    const now = new Date();
    const graceMs = policy.graceDays * 86_400_000;
    const periodDays = policy.rateBasis === 'ANNUAL' ? 365 : policy.rateBasis === 'MONTHLY' ? 30 : 1;
    const dailyRate = new Decimal(policy.ratePercent.toString()).div(100).div(periodDays);

    const invoices = await this.prisma.invoice.findMany({
      where: { organizationId, leaseId, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
      select: { id: true, dueDate: true, interestAccruedTo: true },
    });
    const tx = this.prisma as unknown as Prisma.TransactionClient;
    let total = new Decimal(0);
    const invoiceIds: string[] = [];
    for (const inv of invoices) {
      const graceEnd = new Date(inv.dueDate.getTime() + graceMs);
      const from = inv.interestAccruedTo && inv.interestAccruedTo.getTime() > graceEnd.getTime() ? inv.interestAccruedTo : graceEnd;
      const days = Math.floor((now.getTime() - from.getTime()) / 86_400_000);
      if (days <= 0) continue;
      const { outstanding } = await invoiceArState(tx, organizationId, inv.id);
      if (outstanding.lte(0)) continue;
      const interest = toCents(outstanding.times(dailyRate).times(days));
      if (interest.lte(0)) continue;
      total = total.plus(interest);
      invoiceIds.push(inv.id);
    }
    if (total.lte(0) || invoiceIds.length === 0) return null;
    return { amount: total, description: `Late interest — ${invoiceIds.length} overdue invoice(s)`, chargeTypeId: chargeType.id, invoiceIds, now };
  }

  /** The charges a period yields from the lease's rules and its meters — the
   *  auto-derived part of a debit note, without late interest (which is accrued
   *  once and must not be recomputed on a rebuild). Shared by generate and
   *  regenerate so the two can never drift apart. */
  private async expandPeriod(input: {
    lease: LeaseForBilling;
    leaseUnitIds: string[];
    scopeUnitIds: string[] | null;
    period: string;
    effectiveEnd: Date;
    isFirstInvoice: boolean;
    /** Set when rebuilding, so the note can reclaim the readings it already holds. */
    reclaimFor?: string;
  }): Promise<{ lines: GeneratedLine[]; readingClaims: ReadingClaim[] }> {
    const { lease, leaseUnitIds, scopeUnitIds, period, effectiveEnd, isFirstInvoice } = input;

    // For a split DN: a per-unit rule bills its own unit in full; a whole-lease
    // rule (no unit) is apportioned across the billed units by unit count — e.g.
    // 50k rent over 5 units, billing 3 → 30k. Without a split, every rule bills
    // in full. Assign a rule to a unit (ChargeRule.unitId) to bill that unit its
    // exact amount instead of an even share.
    const totalUnits = leaseUnitIds.length || 1;
    // Each unit's part is a step of the running total rounded to the cent, in a
    // fixed unit order — so however the units are split over notes (a lease's
    // billing groups, every month), the notes add up to the rule's amount.
    const unitOrder = [...leaseUnitIds].sort();
    const apportioned = (amount: Decimal, units: readonly string[]): Decimal =>
      unitOrder.reduce(
        (sum, u, i) =>
          units.includes(u) ? sum.plus(toCents(amount.times(i + 1).dividedBy(totalUnits)).minus(toCents(amount.times(i).dividedBy(totalUnits)))) : sum,
        new Decimal(0),
      );
    const applicableRules = scopeUnitIds
      ? lease.chargeRules.filter((r) => !r.unitId || scopeUnitIds.includes(r.unitId))
      : lease.chargeRules;
    // A rule following the property's standard charge is billed at the standard
    // figure of the units it bills, stretch by stretch (standard-billing.ts) —
    // per unit on a split note, not apportioned, each unit at its own
    // property's — and at its own amount only when none of those units has a
    // figure yet. A unit with none is left out of the sum.
    const history = applicableRules.some((r) => r.followsStandard) ? await loadUnitHistories(this.prisma, lease.organizationId, leaseUnitIds) : [];
    const rules: EngineChargeRule[] = applicableRules.flatMap((r) => {
      const apportion = Boolean(scopeUnitIds) && !r.unitId; // whole-lease rule on a split DN
      const amount = apportion
        ? apportioned(new Decimal(r.amount.toString()), scopeUnitIds!).toFixed(2)
        : r.amount.toString();
      const rule: EngineChargeRule = {
        chargeTypeId: r.chargeTypeId,
        label: apportion ? `${r.chargeType.nameEn} (${scopeUnitIds!.length}/${totalUnits})` : r.chargeType.nameEn,
        amount,
        frequencyMonths: r.frequencyMonths,
        timing: r.timing,
        proration: r.proration,
        firstInvoiceOnly: r.firstInvoiceOnly,
        waivedDuringRentFree: r.chargeType.waivedDuringRentFree,
        startDate: r.startDate,
        endDate: r.endDate,
        sortOrder: r.sortOrder,
      };
      if (!r.followsStandard) return [rule];
      const units = r.unitId ? [r.unitId] : (scopeUnitIds ?? leaseUnitIds);
      return followSegments({
        history,
        chargeTypeId: r.chargeTypeId,
        unitIds: units.length ? units : [null],
        from: r.startDate ?? lease.startDate,
        to: r.endDate,
        effectiveOn: r.proration === 'FULL_MONTH' ? (d) => nextPeriodStart(lease.startDate, r.frequencyMonths, d) : undefined,
        nextPeriod: (d) => nextPeriodStart(lease.startDate, r.frequencyMonths, new Date(d.getTime() + 86_400_000)),
      }).map((s) => ({
        ...rule,
        ...(s.amount === null ? {} : { amount: s.amount, label: r.chargeType.nameEn }),
        startDate: s.start,
        endDate: s.end,
        ...(s.changed.length ? { meta: { standardChanged: s.changed } } : {}),
      }));
    });

    const lines = expandChargeRules({
      // effectiveEnd, not endDate — so an early termination clips the rent-free
      // window with everything else and a tenancy that stops inside its fit-out
      // period simply has nothing left to bill.
      lease: {
        startDate: lease.startDate,
        endDate: effectiveEnd,
        rentFreeFrom: lease.rentFreeFrom,
        rentFreeTo: lease.rentFreeTo,
      },
      rules,
      period,
      isFirstInvoice,
    });
    // Metered utility charges: every reading due on the billed units, not yet
    // billed — but only for the utilities this lease is actually contracted for.
    // A charge rule for the meter's charge type is what authorises it; amount 0
    // is the marker for "billed by meter", since a zero rule emits no fixed line
    // of its own. Read off the rules, never off `lines` above, which by that very
    // token no longer contains the marker. A per-unit rule authorises only its own
    // unit's share, exactly as it bills only its own unit for a fixed charge.
    const billedUnitIds = scopeUnitIds ?? leaseUnitIds;
    const metered = new Map<string, string[]>();
    for (const r of applicableRules) {
      const units = r.unitId ? billedUnitIds.filter((u) => u === r.unitId) : billedUnitIds;
      if (units.length === 0) continue;
      metered.set(r.chargeTypeId, [...new Set([...(metered.get(r.chargeTypeId) ?? []), ...units])]);
    }
    const utility = await this.utilityLinesForPeriod(
      lease.organizationId,
      metered,
      period,
      { tenantId: lease.tenantId, startDate: lease.startDate },
      input.reclaimFor,
    );

    // Charges booked ahead for exactly this month. Like a meter reading, one is
    // consumed by the note that bills it and released if that note is undone, so
    // it can never land on two notes. A unit-scoped one only goes on a note that
    // covers its unit.
    const planned = await this.prisma.plannedCharge.findMany({
      where: {
        leaseId: lease.id,
        period,
        // Two independent conditions that both need an OR, so they go in an AND
        // array. As sibling `OR` keys the second object literal would silently
        // replace the first, and rebuilding a split note — the one call where
        // both are set — would lose the already-billed filter and pull another
        // note's planned charges onto this one.
        AND: [
          input.reclaimFor
            ? { OR: [{ billedInvoiceId: null }, { billedInvoiceId: input.reclaimFor }] }
            : { billedInvoiceId: null },
          ...(scopeUnitIds ? [{ OR: [{ unitId: null }, { unitId: { in: scopeUnitIds } }] }] : []),
        ],
      },
      orderBy: { createdAt: 'asc' },
      include: { chargeType: { select: { nameEn: true } } },
    });

    const generated = [
      ...lines.map((l) => ({
        kind: 'CHARGE' as const,
        chargeTypeId: l.chargeTypeId,
        description: l.description,
        amount: l.amount,
        periodStart: l.periodStart,
        periodEnd: l.periodEnd,
        sortOrder: l.sortOrder,
        // A rent-free line carries the days it gave away, so a short rent can be
        // explained from the line itself; a following rule's line, the standard
        // figures that took effect with it, whose notices the note then shows.
        ...(l.meta ? { meta: l.meta as unknown as Prisma.InputJsonObject } : {}),
      })),
      ...utility.lines.map((u, i) => ({
        kind: 'CHARGE' as const,
        chargeTypeId: u.chargeTypeId,
        description: u.description,
        amount: u.amount,
        periodStart: u.periodStart,
        periodEnd: u.periodEnd,
        sortOrder: 1000 + i,
        // Which reading this charge came out of, so the printed debit note can
        // put the dial photos and the arithmetic behind it on an evidence page.
        meta: u.meta,
      })),
      ...planned.map((p, i) => ({
        kind: 'CHARGE' as const,
        chargeTypeId: p.chargeTypeId,
        description: p.description,
        amount: p.amount.toFixed(2),
        sortOrder: 1500 + i,
        meta: { plannedChargeId: p.id } as Prisma.InputJsonObject,
      })),
    ];
    return { lines: generated, readingClaims: utility.claims };
  }

  /** Rebuilds an unissued debit note's auto-derived charges from the lease's
   *  current rules and meter readings — what you reach for after fixing a rate,
   *  entering a missed reading or correcting the lease.
   *
   *  Only the rule-derived charges are replaced. Manual adjustments, waivers,
   *  deposit/credit applications, a carried-forward balance (its AR is already
   *  posted) and accrued late interest (accruing again would either double-bill
   *  or silently drop it, since the source notes are already marked) all survive
   *  untouched. Changing the total restarts approval, as any other edit does. */
  async regenerateDraft(input: { organizationId: string; invoiceId: string }): Promise<{
    replaced: number;
    kept: number;
    total: string;
  }> {
    const invoice = await this.prisma.invoice.findFirst({
      where: { id: input.invoiceId, organizationId: input.organizationId },
      include: {
        lines: true,
        lease: { include: { chargeRules: { include: { chargeType: true } }, units: { select: { unitId: true } } } },
      },
    });
    if (!invoice) throw new NotFoundException('Debit note not found');
    if (!EDITABLE.includes(invoice.status)) {
      throw new BadRequestException('Only a draft or in-approval debit note can be changed; an approved one must be voided and raised again');
    }

    const lease = invoice.lease;
    if (lease.status !== 'ACTIVE' && lease.status !== 'DRAFT' && lease.status !== 'TERMINATED') {
      throw new BadRequestException(`Cannot bill a ${lease.status} lease`);
    }

    const leaseUnitIds = lease.units.map((u) => u.unitId);
    const scopeUnitIds = (invoice.unitScope as string[] | null) ?? null;
    const start = lease.startDate;
    const isFirstInvoice =
      invoice.billingPeriod === `${start.getUTCFullYear()}-${String(start.getUTCMonth() + 1).padStart(2, '0')}`;

    const { lines: fresh, readingClaims } = await this.expandPeriod({
      lease,
      leaseUnitIds,
      scopeUnitIds,
      period: invoice.billingPeriod,
      effectiveEnd: lease.terminatedAt ?? lease.endDate,
      isFirstInvoice,
      reclaimFor: invoice.id,
    });

    // A rule-derived charge is a CHARGE that nobody hand-added; everything else
    // is either human intent or already reflected in the ledger.
    const isRuleDerived = (l: (typeof invoice.lines)[number]): boolean =>
      l.kind === 'CHARGE' && !(l.meta && typeof l.meta === 'object' && (l.meta as { adjustment?: boolean }).adjustment);
    const stale = invoice.lines.filter(isRuleDerived);
    const kept = invoice.lines.length - stale.length;

    // Refusing an empty rebuild is right when there is genuinely nothing to do,
    // but a period that used to bill and no longer does — a rent-free window
    // recorded after the monthly run raised the draft, a rule deleted, an early
    // termination — must still have its stale lines taken off. Throwing on
    // `kept === 0` would leave the old full-rent line on a note that is still
    // issuable, which is the one outcome this rebuild exists to prevent.
    if (fresh.length === 0 && invoice.lines.length === 0) {
      throw new BadRequestException(`No charges apply for ${invoice.billingPeriod}`);
    }

    await this.prisma.$transaction(async (tx) => {
      if (stale.length) {
        // Evidence was attached to a charge that is about to be replaced; it
        // describes the same underlying reading, so it would be lost silently.
        await tx.attachment.deleteMany({ where: { ownerType: 'INVOICE_LINE', ownerId: { in: stale.map((l) => l.id) } } });
        await tx.invoiceLine.deleteMany({ where: { id: { in: stale.map((l) => l.id) } } });
      }
      if (fresh.length) {
        await tx.invoiceLine.createMany({ data: fresh.map((l) => ({ ...l, invoiceId: invoice.id })) });
      }
      // Re-stake the claim from scratch: a reading this note used to bill but no
      // longer does (the meter left the lease, say) has to become billable again.
      await this.releaseReadings(tx, invoice.id);
      await this.markReadingsBilled(tx, fresh, readingClaims, invoice.id);
      await this.restartApproval(tx, input.organizationId, invoice.id);
    });

    const after = await this.prisma.invoiceLine.findMany({ where: { invoiceId: invoice.id }, select: { amount: true } });
    return { replaced: fresh.length, kept, total: sum(after.map((l) => l.amount.toString())).toFixed(2) };
  }

  /** Sends a DRAFT debit note into its approval workflow (DRAFT →
   *  PENDING_APPROVAL). Opt-in: with no workflow matching the amount there is
   *  nothing to approve and the note is issued directly. */
  async submitForApproval(input: { organizationId: string; invoiceId: string }): Promise<{ workflowName: string; totalSteps: number }> {
    return this.prisma.$transaction(async (tx) => {
      // Claim the transition first; throwing afterwards rolls it back, so an
      // invoice is never left PENDING_APPROVAL without an open round.
      const claim = await tx.invoice.updateMany({
        where: { id: input.invoiceId, organizationId: input.organizationId, status: 'DRAFT' },
        data: { status: 'PENDING_APPROVAL' },
      });
      if (claim.count !== 1) throw new BadRequestException('Only a DRAFT debit note can be sent for approval');

      // Read the total inside the claim, so the workflow is picked for the
      // figures that are actually frozen into this round.
      const invoice = await tx.invoice.findFirstOrThrow({
        where: { id: input.invoiceId },
        select: { lines: { select: { amount: true } } },
      });
      const total = sum(invoice.lines.map((l) => l.amount.toString()));

      const res = await this.approvals.submit(input.organizationId, 'INVOICE', input.invoiceId, total, tx);
      if (!res.required) throw new BadRequestException('No approval workflow applies to this debit note — issue it directly');
      return { workflowName: res.workflowName ?? '', totalSteps: res.totalSteps ?? 0 };
    });
  }

  /** The debit note's approval picture for the signed-in user (drives the
   *  approval box in the detail dialog). */
  async approvalState(input: { organizationId: string; invoiceId: string; userId: string }) {
    const invoice = await this.prisma.invoice.findFirst({
      where: { id: input.invoiceId, organizationId: input.organizationId },
      include: { lines: { select: { amount: true } } },
    });
    if (!invoice) throw new NotFoundException('Debit note not found');
    const total = sum(invoice.lines.map((l) => l.amount.toString()));
    return this.approvals.documentState(input.organizationId, 'INVOICE', invoice.id, input.userId, total);
  }

  /** Issues a debit note: assigns a number and posts the balanced journal entry
   *  (DR Accounts Receivable / CR each charge's income account). Issuable from
   *  DRAFT when no workflow applies, or from APPROVED once every step signed. */
  async issue(input: {
    organizationId: string;
    invoiceId: string;
    issuedByUserId?: string | null;
    /** A number the office typed for this note; none takes the next in sequence. */
    number?: string | null;
  }): Promise<InvoiceWithLines> {
    const pre = await this.prisma.invoice.findFirst({
      where: { id: input.invoiceId, organizationId: input.organizationId },
      include: { lines: { select: { amount: true } } },
    });
    if (pre?.status === 'PENDING_APPROVAL') {
      throw new BadRequestException('This debit note is awaiting approval; it can be issued once every step has signed off.');
    }
    if (pre?.status === 'DRAFT') {
      // Opt-in gate: a workflow matching this amount must be walked explicitly
      // first, so approval is a visible stage rather than a side effect of issuing.
      const total = sum(pre.lines.map((l) => l.amount.toString()));
      const wf = await this.approvals.requirementFor(input.organizationId, 'INVOICE', total);
      if (wf) {
        throw new BadRequestException(`This debit note needs approval — send it to the "${wf.name}" workflow before issuing.`);
      }
    }

    const result = await this.prisma.$transaction(async (tx) => {
      // First of all: issuing draws the lease's credit (lease-credit.ts lockLeases).
      await lockLeases(tx, [pre?.leaseId]);
      // Compare-and-swap: atomically claim the →ISSUED transition. updateMany is
      // a locking write, so a concurrent/double-clicked issue on the same invoice
      // sees status already ISSUED and gets count 0 → no double posting.
      const claim = await tx.invoice.updateMany({
        where: { id: input.invoiceId, organizationId: input.organizationId, status: { in: ['DRAFT', 'APPROVED'] } },
        // Clearing the schedule in the same claim means a note issued by hand
        // leaves the queue atomically — the job can never pick it up after.
        data: { status: 'ISSUED', scheduledIssueDate: null },
      });
      if (claim.count !== 1) {
        throw new BadRequestException('Only an unissued debit note can be issued (already issued or not found)');
      }

      const invoice = await tx.invoice.findFirstOrThrow({
        where: { id: input.invoiceId },
        include: { lines: { include: { chargeType: { include: { glAccount: true } } } } },
      });

      // Freeze the payee onto the note as it is issued. A debit note tells the
      // tenant where to send the money, and that instruction has to stay what it
      // said on the day: re-printing a note from two years ago must not show an
      // account the company has since closed. The lease's own account wins;
      // failing that the organisation's collection account.
      const payee =
        (await tx.bankAccount.findFirst({ where: { id: invoice.bankAccountId ?? '', organizationId: input.organizationId } })) ??
        (await defaultCollectionAccount(tx, input.organizationId));
      if (payee) {
        await tx.invoice.update({
          where: { id: invoice.id },
          data: {
            bankAccountId: invoice.bankAccountId ?? payee.id,
            payeeSnapshot: { accountName: payee.accountName, bankName: payee.bankName, accountNumber: payee.accountNumber },
          },
        });
      }

      // Freeze the letterhead for the same reason: a debit note says who billed
      // the tenant, and that is as much a part of what it said as where to pay.
      // The building may be moved to another owning company, or the company may
      // move office, long before an old note is re-printed. Written for the
      // organisation's own heading too — freezing only the landlord case would
      // leave the company's own address free to rewrite its history.
      const lease = await tx.lease.findFirstOrThrow({
        where: { id: invoice.leaseId },
        select: { units: { select: { unit: { select: { property: { select: letterheadPropertySelect } } } } } },
      });
      const properties = propertiesOf(lease.units);
      const org = await tx.organization.findFirstOrThrow({ where: { id: input.organizationId } });
      await tx.invoice.update({
        where: { id: invoice.id },
        data: { letterheadSnapshot: { ...leaseLetterhead(org, properties) } },
      });

      const ar = await systemAccount(tx, input.organizationId, 'RECEIVABLE');

      // Carry-forward (b/f) lines already had their AR posted when the balance
      // was carried; they're display-only here and must not post again.
      const chargeLines = invoice.lines.filter((l) => l.kind !== 'OVERDUE_CARRYFORWARD');

      // Positive line → CREDIT its income account; negative (waiver/concession) →
      // DEBIT it. AR carries the net, so the entry balances for any mix, and a
      // fully-offset (zero-net) invoice still posts its gross legs.
      const ledgerLines: LedgerLineInput[] = [];
      for (const line of chargeLines) {
        const amt = new Decimal(line.amount.toString());
        if (amt.isZero()) continue;
        const account = line.chargeType?.glAccount;
        if (!account) {
          throw new BadRequestException(
            `Charge type for line "${line.description}" has no GL account; set one before issuing.`,
          );
        }
        ledgerLines.push({
          accountId: account.id,
          direction: amt.isNegative() ? 'DEBIT' : 'CREDIT',
          amount: amt.abs().toFixed(2),
          leaseId: invoice.leaseId,
          invoiceId: invoice.id,
        });
      }

      const net = sum(chargeLines.map((l) => l.amount.toString()));
      if (net.greaterThan(0)) {
        ledgerLines.push({ accountId: ar.id, direction: 'DEBIT', amount: net.toFixed(2), leaseId: invoice.leaseId, invoiceId: invoice.id });
      } else if (net.lessThan(0)) {
        ledgerLines.push({ accountId: ar.id, direction: 'CREDIT', amount: net.abs().toFixed(2), leaseId: invoice.leaseId, invoiceId: invoice.id });
      }

      const issueDate = new Date();
      const number = await this.numbers.assign(tx, input.organizationId, 'INVOICE', input.number, { date: issueDate, propertyIds: properties.map((p) => p.id) });

      // A pure carry-forward DN (only b/f lines) has nothing new to post.
      if (ledgerLines.length > 0) {
        await this.ledger.post(tx, {
          organizationId: input.organizationId,
          entryDate: issueDate,
          sourceType: 'INVOICE',
          createdById: input.issuedByUserId ?? null,
          sourceId: invoice.id,
          currency: invoice.currency,
          memo: `Invoice ${number}`,
          lines: ledgerLines,
        });
      }

      await tx.invoice.update({ where: { id: invoice.id }, data: { number, issueDate } });

      // Money the tenant already paid for this lease — a deposit receipt, or the
      // overpaid part of an earlier payment — pays the note as it goes out.
      await applyLeaseCredit(tx, this.ledger, input.organizationId, invoice.leaseId, {
        invoiceIds: [invoice.id],
        createdById: input.issuedByUserId ?? null,
      });

      return tx.invoice.findFirstOrThrow({ where: { id: invoice.id }, include: { lines: { orderBy: { sortOrder: 'asc' } } } });
    });
    try {
      await this.events.emitAsync('notify', {
        event: 'INVOICE_ISSUED',
        organizationId: input.organizationId,
        relatedType: 'INVOICE',
        relatedId: result.id,
      });
    } catch {
      // notifications are best-effort
    }
    return result;
  }

  /** Voids an invoice — the append-only alternative to deletion.
   *  - DRAFT (never posted): simply marked VOID.
   *  - ISSUED and still fully unpaid, with no receipt/carry-forward activity: the
   *    original journal entry is reversed (mirror entry) and the invoice marked VOID.
   *  Anything with payments, deposit applications or carry-forward is refused —
   *  those must be unwound first, so the ledger is never left inconsistent. */
  /** Defers this debit note's issue to a chosen date; null cancels. Nothing else
   *  changes — it keeps its status, has no number and no ledger entry, and the
   *  tenant still cannot see it. On the day the scheduler calls issue(). */
  async setSchedule(input: { organizationId: string; invoiceId: string; date: Date | null }): Promise<InvoiceWithLines> {
    if (input.date && input.date <= hkToday()) {
      throw new BadRequestException('Pick a date after today; to send it now use Issue.');
    }
    const claim = await this.prisma.invoice.updateMany({
      where: { id: input.invoiceId, organizationId: input.organizationId, status: { in: ['DRAFT', 'APPROVED'] } },
      data: { scheduledIssueDate: input.date },
    });
    if (claim.count !== 1) {
      throw new BadRequestException('Only an unissued debit note can be scheduled (already issued or not found)');
    }
    return this.prisma.invoice.findFirstOrThrow({
      where: { id: input.invoiceId },
      include: { lines: { orderBy: { sortOrder: 'asc' } } },
    });
  }

  /** Issues every note whose scheduled day has arrived. issue() is reused
   *  unchanged, so approval, the GL accounts and the →ISSUED claim are all
   *  re-checked on the day, exactly as if a human had pressed the button. One
   *  that cannot be issued keeps its date and is reported rather than dropped —
   *  a date in the past with the note still unissued is how "it should have gone
   *  out and didn't" is visible at all. */
  async issueScheduled(): Promise<{ due: number; issued: number; failures: { invoiceId: string; organizationId: string; message: string }[] }> {
    const orgs = await this.prisma.organization.findMany({ where: { deletedAt: null }, select: { id: true } });
    const due = await this.prisma.invoice.findMany({
      where: {
        organizationId: { in: orgs.map((o) => o.id) },
        status: { in: ['DRAFT', 'APPROVED'] },
        scheduledIssueDate: { lte: hkToday() },
        lease: { deletedAt: null },
      },
      orderBy: [{ scheduledIssueDate: 'asc' }, { id: 'asc' }],
      select: { id: true, organizationId: true },
    });
    const failures: { invoiceId: string; organizationId: string; message: string }[] = [];
    let issued = 0;
    for (const inv of due) {
      try {
        await this.issue({ organizationId: inv.organizationId, invoiceId: inv.id });
        issued += 1;
      } catch (e) {
        failures.push({ invoiceId: inv.id, organizationId: inv.organizationId, message: e instanceof Error ? e.message : String(e) });
      }
    }
    return { due: due.length, issued, failures };
  }

  async voidInvoice(input: { organizationId: string; invoiceId: string }): Promise<InvoiceWithLines> {
    const target = await this.prisma.invoice.findFirst({ where: { id: input.invoiceId, organizationId: input.organizationId }, select: { leaseId: true } });
    return this.prisma.$transaction(async (tx) => {
      // First of all, so a payment or a drawing of credit landing on this note
      // meanwhile is seen by the checks below (lease-credit.ts lockLeases).
      await lockLeases(tx, [target?.leaseId]);
      const invoice = await tx.invoice.findFirst({
        where: { id: input.invoiceId, organizationId: input.organizationId },
        include: { lines: true },
      });
      if (!invoice) throw new NotFoundException('Debit note not found');
      if (invoice.status === 'VOID') throw new BadRequestException('This debit note is already void');

      if (PRE_ISSUE.includes(invoice.status)) {
        // A normal draft has no ledger entry — but a carry-forward *target* is a
        // DRAFT that already received an ADJUSTMENT AR posting when a balance was
        // carried onto it. Voiding it as if it were ledger-free would strand that
        // receivable, so refuse any draft that has carried-forward activity.
        if (invoice.lines.some((l) => l.kind === 'OVERDUE_CARRYFORWARD')) {
          throw new BadRequestException('This draft carries a balance forwarded from another debit note; handle the carry-forward before voiding.');
        }
        const arActivity = await tx.journalLine.count({ where: { invoiceId: invoice.id } });
        if (arActivity > 0) {
          throw new BadRequestException('This draft has ledger activity (a carried-forward balance) and cannot be voided directly.');
        }
        const claim = await tx.invoice.updateMany({ where: { id: invoice.id, status: { in: PRE_ISSUE } }, data: { status: 'VOID' } });
        if (claim.count !== 1) throw new ConflictException('Debit note changed state; please retry');
        // Nothing left to sign off on — close any round still in flight.
        await this.approvals.supersede('INVOICE', invoice.id, tx);
        // Its metered charges are gone, so those readings are unbilled again.
        await this.releaseReadings(tx, invoice.id);
        return tx.invoice.findFirstOrThrow({ where: { id: invoice.id }, include: { lines: { orderBy: { sortOrder: 'asc' } } } });
      }

      if (invoice.status !== 'ISSUED') {
        throw new BadRequestException('Only an unissued, or a fully-unpaid ISSUED, debit note can be voided. Reverse the payments first.');
      }
      if (invoice.lines.some((l) => l.kind === 'OVERDUE_CARRYFORWARD')) {
        throw new BadRequestException('This debit note carries a balance forwarded from another debit note; handle the carry-forward before voiding.');
      }
      // Any AR movement on this invoice other than its own issue posting (a receipt,
      // deposit application, drawing of credit or carry-forward transfer) that still
      // stands means it is not clean — refuse rather than leave a half-unwound
      // balance. One already reversed — a bounced receipt, a withdrawn drawing —
      // has been unwound, which is what this asks for, so it and its reversal
      // no longer count; counting them left such a note impossible to void.
      const ar = await findSystemAccount(tx, input.organizationId, 'RECEIVABLE');
      if (ar) {
        const moves = await tx.journalLine.findMany({
          where: { accountId: ar.id, invoiceId: invoice.id, entry: { sourceType: { not: 'INVOICE' } } },
          select: { entry: { select: { id: true, reversesId: true } } },
        });
        const undone = new Set(
          (await tx.journalEntry.findMany({ where: { reversesId: { in: moves.map((m) => m.entry.id) } }, select: { reversesId: true } })).map((e) => e.reversesId),
        );
        const touched = moves.filter((m) => m.entry.reversesId === null && !undone.has(m.entry.id)).length;
        if (touched > 0) {
          throw new BadRequestException('This debit note has payment or carry-forward activity; reverse those before voiding.');
        }
      }
      // A PENDING receipt hasn't posted to the ledger yet, so the AR check above
      // can't see it — but approving it after a void would re-post AR and resurrect
      // the invoice (VOID→PAID, AR negative). Refuse while one is outstanding.
      const pendingReceipts = await tx.receipt.count({
        where: {
          organizationId: input.organizationId,
          status: 'PENDING',
          allocations: { some: { items: { some: { invoiceId: invoice.id } } } },
        },
      });
      if (pendingReceipts > 0) {
        throw new BadRequestException('This debit note has a pending receipt; reject or approve it before voiding.');
      }

      // CAS-claim ISSUED→VOID so a concurrent payment can't slip in.
      const claim = await tx.invoice.updateMany({ where: { id: invoice.id, status: 'ISSUED' }, data: { status: 'VOID' } });
      if (claim.count !== 1) throw new ConflictException('Debit note changed state; please retry');
      await this.releaseReadings(tx, invoice.id);

      const entry = await tx.journalEntry.findFirst({
        where: { organizationId: input.organizationId, sourceType: 'INVOICE', sourceId: invoice.id },
      });
      if (entry) {
        await this.ledger.reverse(tx, {
          entryId: entry.id,
          entryDate: new Date(),
          memo: `Void invoice ${invoice.number ?? invoice.id}`,
        });
      }
      return tx.invoice.findFirstOrThrow({ where: { id: invoice.id }, include: { lines: { orderBy: { sortOrder: 'asc' } } } });
    });
  }

  /** A lease's billing groups: the units of each of its monthly notes, in group
   * order with the ungrouped units together last — or null when no unit is
   * grouped, and the lease is billed on one note. */
  private billingGroupsOf(units: readonly { unitId: string; billingGroup: string | null }[]): string[][] | null {
    if (!units.some((u) => u.billingGroup)) return null;
    const groups = new Map<string, string[]>();
    for (const u of units) groups.set(u.billingGroup ?? '', [...(groups.get(u.billingGroup ?? '') ?? []), u.unitId]);
    return [...groups.keys()]
      .sort((a, b) => (a === '' ? 1 : b === '' ? -1 : a.localeCompare(b, undefined, { numeric: true })))
      .map((key) => groups.get(key)!);
  }

  /** Raises a lease's notes for a period by its billing groups, one per group,
   * passing over a group with any unit already on a live note for the period
   * (a whole-lease note covers them all) — so no unit is billed twice, and
   * running it again raises only the notes still missing. A group with nothing
   * to bill this month is passed over too. */
  async generateGroupDrafts(input: { organizationId: string; leaseId: string; period: string }): Promise<{ created: number; skipped: number }> {
    const lease = await this.prisma.lease.findFirst({
      where: { id: input.leaseId, organizationId: input.organizationId, deletedAt: null },
      select: { units: { select: { unitId: true, billingGroup: true } } },
    });
    if (!lease) throw new NotFoundException('Lease not found');
    const groups = this.billingGroupsOf(lease.units);
    if (!groups) throw new BadRequestException('This lease has no billing groups');
    const live = await this.prisma.invoice.findMany({
      where: { leaseId: input.leaseId, billingPeriod: input.period, status: { not: 'VOID' } },
      select: { unitScope: true },
    });
    const onANote = (unitId: string) => live.some((n) => n.unitScope === null || (n.unitScope as string[]).includes(unitId));
    let created = 0;
    let skipped = 0;
    for (const unitIds of groups) {
      if (unitIds.some(onANote)) {
        skipped += 1;
        continue;
      }
      try {
        await this.generateDraft({ organizationId: input.organizationId, leaseId: input.leaseId, period: input.period, unitIds });
        created += 1;
      } catch (err) {
        if (!(err instanceof BadRequestException && err.message.startsWith('No charges apply'))) throw err;
        skipped += 1;
      }
    }
    return { created, skipped };
  }

  /** The monthly billing run: generate DRAFT invoices for every active lease
   * that doesn't already have one for the period — a lease with billing groups
   * one per group (generateGroupDrafts). Idempotent — safe to re-run and safe to
   * call from a scheduler. Never issues; a human reviews the drafts. */
  async generateDraftsForPeriod(input: {
    organizationId: string;
    period: string;
  }): Promise<{ created: number; skipped: number; leaseCount: number }> {
    const leases = await this.prisma.lease.findMany({
      where: { organizationId: input.organizationId, status: 'ACTIVE', deletedAt: null },
      select: { id: true, units: { select: { billingGroup: true } } },
    });
    // A lease may carry several notes for one month deliberately (rent on one,
    // utilities on another), so the monthly run needs its own guard: a human
    // making a second note is not licence for the scheduler to make a third
    // every time it runs.
    const already = new Set(
      (
        await this.prisma.invoice.findMany({
          where: {
            organizationId: input.organizationId,
            leaseId: { in: leases.map((l) => l.id) },
            billingPeriod: input.period,
            status: { not: 'VOID' },
          },
          select: { leaseId: true },
          distinct: ['leaseId'],
        })
      ).map((i) => i.leaseId),
    );
    let created = 0;
    let skipped = 0;
    for (const lease of leases) {
      // Billed on several notes a month: each group's, guarded group by group.
      if (lease.units.some((u) => u.billingGroup)) {
        const r = await this.generateGroupDrafts({ organizationId: input.organizationId, leaseId: lease.id, period: input.period }).catch(() => ({
          created: 0,
          skipped: 1,
        }));
        created += r.created;
        skipped += r.skipped;
        continue;
      }
      if (already.has(lease.id)) {
        skipped += 1;
        continue;
      }
      try {
        await this.generateDraft({ organizationId: input.organizationId, leaseId: lease.id, period: input.period });
        created += 1;
      } catch {
        // No charges apply for this lease → skip it.
        skipped += 1;
      }
    }
    return { created, skipped, leaseCount: leases.length };
  }

  /** Lease lifecycle transition (run before each billing run): activate scheduled
   * renewals whose term has begun, end leases past their term, and carry a
   * same-tenant renewal's held deposit over to the new lease. Idempotent. */
  async transitionLeases(input: { organizationId: string; asOf: Date }): Promise<{ activated: number; ended: number; depositsMoved: number }> {
    const { organizationId, asOf } = input;
    return this.prisma.$transaction(async (tx) => {
      // Leases whose term has finished (endDate before now) and are still active.
      const expiring = await tx.lease.findMany({
        where: { organizationId, status: 'ACTIVE', deletedAt: null, endDate: { lt: asOf } },
        select: { id: true, tenantId: true },
      });
      // Carry each expiring lease's held deposit(s) over to its same-tenant renewal.
      let depositsMoved = 0;
      for (const old of expiring) {
        const renewal = await tx.lease.findFirst({
          where: { organizationId, renewedFromId: old.id, tenantId: old.tenantId, deletedAt: null },
          select: { id: true },
        });
        if (!renewal) continue;
        const moved = await tx.deposit.updateMany({
          // PARTIALLY_APPLIED too: the rest of the deposits module treats both
          // as live money (apply, awaitingSettlement, heldForLease all do), so
          // leaving one pinned to the lease being ended mis-attributes it.
          where: { organizationId, leaseId: old.id, status: { in: ['HELD', 'PARTIALLY_APPLIED'] } },
          data: { leaseId: renewal.id },
        });
        depositsMoved += moved.count;
      }
      // Activate scheduled renewals whose new term has started.
      const activated = await tx.lease.updateMany({
        where: { organizationId, status: 'DRAFT', deletedAt: null, renewedFromId: { not: null }, startDate: { lte: asOf } },
        data: { status: 'ACTIVE' },
      });
      // End the expired leases.
      const ended = await tx.lease.updateMany({
        where: { id: { in: expiring.map((l) => l.id) } },
        data: { status: 'ENDED' },
      });
      return { activated: activated.count, ended: ended.count, depositsMoved };
    });
  }

  /** Ends a tenancy before its contracted endDate. Records when and why, then
   *  raises the final part-month debit note — the engine clips every line to the
   *  termination date, so the proration falls out of the existing rules.
   *
   *  The final note is best-effort: a period that is already billed, or one with
   *  nothing left to charge, leaves the lease terminated and reports why rather
   *  than failing the termination. Outstanding notes and held deposits do NOT
   *  block — a move-out normally has both, and the deposit settlement is where
   *  they get squared off. */
  async terminateLease(input: {
    organizationId: string;
    leaseId: string;
    terminationDate: Date;
    reason?: string | null;
  }): Promise<{ leaseId: string; finalInvoiceId: string | null; finalInvoiceSkipped: 'ALREADY_BILLED' | 'NOTHING_TO_BILL' | null }> {
    const lease = await this.prisma.lease.findFirst({
      where: { id: input.leaseId, organizationId: input.organizationId, deletedAt: null },
      select: { id: true, status: true, startDate: true, endDate: true },
    });
    if (!lease) throw new NotFoundException('Lease not found');
    if (lease.status !== 'ACTIVE') throw new BadRequestException('Only an active lease can be terminated');
    if (input.terminationDate.getTime() < lease.startDate.getTime()) {
      throw new BadRequestException('The termination date cannot be before the lease starts');
    }
    if (input.terminationDate.getTime() > lease.endDate.getTime()) {
      throw new BadRequestException('The termination date is on or after the contracted end; let the lease run to term instead');
    }

    // CAS on ACTIVE: two concurrent terminations must not both raise a final note.
    const claim = await this.prisma.lease.updateMany({
      where: { id: lease.id, organizationId: input.organizationId, status: 'ACTIVE' },
      data: { status: 'TERMINATED', terminatedAt: input.terminationDate, terminationReason: input.reason?.trim() || null },
    });
    if (claim.count !== 1) throw new ConflictException('Lease changed state; please retry');

    const period = `${input.terminationDate.getUTCFullYear()}-${String(input.terminationDate.getUTCMonth() + 1).padStart(2, '0')}`;
    const alreadyBilled = await this.prisma.invoice.findFirst({
      where: { leaseId: lease.id, billingPeriod: period, status: { not: 'VOID' } },
      select: { id: true },
    });
    if (alreadyBilled) return { leaseId: lease.id, finalInvoiceId: null, finalInvoiceSkipped: 'ALREADY_BILLED' };

    try {
      const final = await this.generateDraft({ organizationId: input.organizationId, leaseId: lease.id, period });
      return { leaseId: lease.id, finalInvoiceId: final.id, finalInvoiceSkipped: null };
    } catch (err) {
      // "No charges apply for <period>" is a normal outcome here (e.g. every rule
      // is arrears-billed and already covered). Anything else is a real failure.
      if (err instanceof BadRequestException) {
        return { leaseId: lease.id, finalInvoiceId: null, finalInvoiceSkipped: 'NOTHING_TO_BILL' };
      }
      throw err;
    }
  }

  /** Debit notes on a lease that still need attention: issued-but-unpaid ones
   *  with their ledger-derived outstanding, and any not yet issued (whose whole
   *  total is still open). Drives the warnings on the termination dialog. */
  async leaseOpenInvoices(organizationId: string, leaseId: string) {
    const rows = await this.prisma.invoice.findMany({
      where: { organizationId, leaseId, status: { in: [...PRE_ISSUE, 'ISSUED', 'PARTIALLY_PAID'] } },
      orderBy: { billingPeriod: 'asc' },
      include: { lines: { select: { amount: true } } },
    });
    const tx = this.prisma as unknown as Prisma.TransactionClient;
    const out: { id: string; number: string | null; billingPeriod: string; status: string; currency: string; outstanding: string }[] = [];
    for (const inv of rows) {
      const issued = inv.status === 'ISSUED' || inv.status === 'PARTIALLY_PAID';
      const outstanding = issued
        ? (await invoiceArState(tx, organizationId, inv.id)).outstanding
        : sum(inv.lines.map((l) => l.amount.toString()));
      out.push({
        id: inv.id,
        number: inv.number,
        billingPeriod: inv.billingPeriod,
        status: inv.status,
        currency: inv.currency,
        outstanding: outstanding.toFixed(2),
      });
    }
    return out;
  }

  /** Adds a manual adjustment line to a DRAFT debit note before it is issued —
   * a waiver/concession (credit → negative) or a one-off charge (positive). The
   * charge type carries the GL account it posts to when issued. Marked in `meta`
   * so it can be told apart from the auto-generated lines and removed later. */
  async addAdjustment(input: { organizationId: string; invoiceId: string; chargeTypeId: string; description: string; amount: string; credit: boolean }): Promise<void> {
    const inv = await this.prisma.invoice.findFirst({ where: { id: input.invoiceId, organizationId: input.organizationId }, select: { status: true } });
    if (!inv) throw new NotFoundException('Debit note not found');
    if (!EDITABLE.includes(inv.status)) throw new BadRequestException('Only a draft or in-approval debit note can be changed; an approved one must be voided and raised again');
    const ct = await this.prisma.chargeType.findFirst({
      where: { id: input.chargeTypeId, organizationId: input.organizationId, glAccountId: { not: null } },
      select: { id: true },
    });
    if (!ct) throw new BadRequestException('Pick a charge type with a GL account');
    const amt = new Decimal(input.amount);
    if (amt.lte(0)) throw new BadRequestException('Amount must be positive');
    await this.prisma.$transaction(async (tx) => {
      const last = await tx.invoiceLine.aggregate({ where: { invoiceId: input.invoiceId }, _max: { sortOrder: true } });
      await tx.invoiceLine.create({
        data: {
          invoiceId: input.invoiceId,
          kind: input.credit ? 'WAIVER' : 'CHARGE',
          chargeTypeId: input.chargeTypeId,
          description: input.description,
          amount: (input.credit ? amt.negated() : amt).toFixed(2),
          sortOrder: (last._max.sortOrder ?? 0) + 10,
          meta: { adjustment: true },
        },
      });
      await this.restartApproval(tx, input.organizationId, input.invoiceId);
    });
  }

  /** Waives accrued late interest on an unissued note by removing its INTEREST
   * line(s). The source invoices stay marked accrued, so the same days aren't
   * re-billed. */
  async waiveInterest(input: { organizationId: string; invoiceId: string }): Promise<{ removed: number }> {
    const inv = await this.prisma.invoice.findFirst({ where: { id: input.invoiceId, organizationId: input.organizationId }, select: { status: true } });
    if (!inv) throw new NotFoundException('Debit note not found');
    if (!EDITABLE.includes(inv.status)) throw new BadRequestException('Only a draft or in-approval debit note can be changed; an approved one must be voided and raised again');
    return this.prisma.$transaction(async (tx) => {
      const res = await tx.invoiceLine.deleteMany({ where: { invoiceId: input.invoiceId, kind: 'INTEREST' } });
      if (res.count > 0) await this.restartApproval(tx, input.organizationId, input.invoiceId);
      return { removed: res.count };
    });
  }

  /** Removes a line from an unissued debit note. A draft is a working document —
   *  the rules expand into it so nobody types every charge by hand, and what is
   *  not wanted comes off. The three kinds that cannot are the ones whose money
   *  has already moved: a carried-forward balance and a deposit or credit
   *  application all posted to the ledger when they were put on. */
  async removeLine(input: { organizationId: string; lineId: string }): Promise<void> {
    const line = await this.prisma.invoiceLine.findFirst({
      where: { id: input.lineId, invoice: { organizationId: input.organizationId } },
      select: { id: true, kind: true, meta: true, invoiceId: true, invoice: { select: { status: true } } },
    });
    if (!line) throw new NotFoundException('Line not found');
    if (!EDITABLE.includes(line.invoice.status)) throw new BadRequestException('Only a draft or in-approval debit note can be changed; an approved one must be voided and raised again');
    if (POSTED_LINE_KINDS.includes(line.kind)) {
      throw new BadRequestException('This line is already posted to the ledger and cannot be removed; void the debit note instead');
    }
    const meta = line.meta && typeof line.meta === 'object' ? (line.meta as { meterReadingId?: unknown; unitId?: unknown; plannedChargeId?: unknown }) : {};
    const readingId = meta.meterReadingId;
    const plannedId = meta.plannedChargeId;
    await this.prisma.$transaction(async (tx) => {
      await tx.invoiceLine.delete({ where: { id: input.lineId } });
      // A reading is billed one unit's share per line, so taking a line off
      // releases that unit's share, and only that.
      if (typeof readingId === 'string') {
        if (typeof meta.unitId === 'string') {
          await tx.meterReadingClaim.deleteMany({ where: { readingId, unitId: meta.unitId, invoiceId: line.invoiceId } });
        } else {
          // A line from before shares were claimed per unit names no unit: its
          // reading's claims on this note go once the last of its lines does.
          const stillHere = await tx.invoiceLine.count({
            where: { invoiceId: line.invoiceId, meta: { path: '$.meterReadingId', equals: readingId } },
          });
          if (stillHere === 0) await tx.meterReadingClaim.deleteMany({ where: { readingId, invoiceId: line.invoiceId } });
        }
      }
      // A planned charge makes exactly one line, so taking that line off the note
      // releases it outright. Without this it stays stamped as billed by a note
      // it is no longer on: no future note will pick it up (they only reclaim
      // unclaimed ones) and the lease screen refuses to delete it, so a charge
      // that was booked on purpose is silently billed to nobody.
      if (typeof plannedId === 'string') {
        await tx.plannedCharge.updateMany({ where: { id: plannedId, billedInvoiceId: line.invoiceId }, data: { billedInvoiceId: null } });
      }
      await this.restartApproval(tx, input.organizationId, line.invoiceId);
    });
  }

  /** A change to a debit note that is in (or has cleared) approval invalidates
   * the signatures collected so far: that round is superseded and, if a workflow
   * still applies at the new total, a fresh round opens at step 1. When the new
   * total no longer meets any threshold the note simply returns to DRAFT. */
  private async restartApproval(tx: Prisma.TransactionClient, organizationId: string, invoiceId: string): Promise<void> {
    const inv = await tx.invoice.findFirstOrThrow({
      where: { id: invoiceId },
      select: { status: true, lines: { select: { amount: true } } },
    });
    // A change to the figures cancels a deferred send too — the date was chosen
    // for what the note said then. Cleared before the early return below,
    // because a draft with no workflow can carry a schedule just the same.
    await tx.invoice.updateMany({ where: { id: invoiceId, scheduledIssueDate: { not: null } }, data: { scheduledIssueDate: null } });
    if (inv.status !== 'PENDING_APPROVAL' && inv.status !== 'APPROVED') return;
    await this.approvals.supersede('INVOICE', invoiceId, tx);
    const total = sum(inv.lines.map((l) => l.amount.toString()));
    const res = await this.approvals.submit(organizationId, 'INVOICE', invoiceId, total, tx);
    await tx.invoice.update({
      where: { id: invoiceId },
      data: { status: res.required ? 'PENDING_APPROVAL' : 'DRAFT' },
    });
  }

  /** Carries an invoice's outstanding balance onto the lease's next (draft) DN as
   * a "balance b/f" line, moving the AR so the source closes and the tenant sees
   * the full amount owed on the latest DN. Ledger stays balanced and append-only. */
  async carryForward(input: {
    organizationId: string;
    invoiceId: string;
    targetPeriod?: string;
    carriedByUserId?: string | null;
  }): Promise<InvoiceWithLines> {
    return this.prisma.$transaction(async (tx) => {
      const source = await tx.invoice.findFirst({
        where: { id: input.invoiceId, organizationId: input.organizationId },
        include: { lease: true },
      });
      if (!source) throw new NotFoundException('Debit note not found');
      if (source.status !== 'ISSUED' && source.status !== 'PARTIALLY_PAID') {
        throw new BadRequestException('Only an issued, still-owed debit note can be carried forward');
      }
      const { outstanding } = await invoiceArState(tx, input.organizationId, source.id);
      if (outstanding.lte(0)) throw new BadRequestException('This debit note has nothing outstanding to carry');

      const targetPeriod = input.targetPeriod ?? this.nextPeriod(source.billingPeriod);

      const blocking = await tx.invoice.findFirst({
        where: {
          leaseId: source.leaseId,
          billingPeriod: targetPeriod,
          status: { in: ['ISSUED', 'PARTIALLY_PAID', 'PAID'] },
        },
      });
      if (blocking) {
        throw new BadRequestException(`The ${targetPeriod} debit note is already issued; carry-forward needs a draft target`);
      }

      let target = await tx.invoice.findFirst({
        where: { leaseId: source.leaseId, billingPeriod: targetPeriod, status: { in: PRE_ISSUE } },
        orderBy: { createdAt: 'asc' },
      });
      if (target && target.currency !== source.currency) {
        throw new BadRequestException(
          `The ${targetPeriod} draft is in ${target.currency}, not ${source.currency}; carry-forward cannot mix currencies.`,
        );
      }
      if (!target) {
        target = await tx.invoice.create({
          data: {
            organizationId: input.organizationId,
            leaseId: source.leaseId,
            bankAccountId: source.lease.bankAccountId,
            status: 'DRAFT',
            currency: source.currency,
            billingPeriod: targetPeriod,
            dueDate: this.computeDueDate(targetPeriod, source.lease.dueDayOfMonth),
          },
        });
      }

      await tx.invoiceLine.create({
        data: {
          invoiceId: target.id,
          kind: 'OVERDUE_CARRYFORWARD',
          description: `Balance b/f from ${source.number ?? source.billingPeriod}`,
          amount: outstanding.toFixed(2),
          sourceInvoiceId: source.id,
          sortOrder: -100,
        },
      });
      // The target's total just moved — any approval it had must be re-walked.
      await this.restartApproval(tx, input.organizationId, target.id);

      const ar = await systemAccount(tx, input.organizationId, 'RECEIVABLE');

      // Same-account AR transfer: move the balance from source → target invoice.
      await this.ledger.post(tx, {
        organizationId: input.organizationId,
        entryDate: new Date(),
        sourceType: 'ADJUSTMENT',
        createdById: input.carriedByUserId ?? null,
        sourceId: target.id,
        currency: source.currency,
        memo: `Carry forward ${source.number ?? source.billingPeriod} → ${targetPeriod}`,
        lines: [
          { accountId: ar.id, direction: 'DEBIT', amount: outstanding.toFixed(2), leaseId: source.leaseId, invoiceId: target.id },
          { accountId: ar.id, direction: 'CREDIT', amount: outstanding.toFixed(2), leaseId: source.leaseId, invoiceId: source.id },
        ],
      });

      const srcState = await invoiceArState(tx, input.organizationId, source.id);
      await tx.invoice.update({
        where: { id: source.id },
        data: { status: deriveInvoiceStatus(srcState), note: `Carried forward to ${targetPeriod}` },
      });

      return tx.invoice.findFirstOrThrow({
        where: { id: target.id },
        include: { lines: { orderBy: { sortOrder: 'asc' } } },
      });
    });
  }

  /** Undo a carry-forward: put the balance back on the note it came from.
   *
   *  A carry-forward posts an AR→AR transfer, so the line cannot simply be
   *  deleted — removeLine refuses it for that reason, and voiding either note is
   *  refused too. Booked into the wrong period it was uncorrectable, and the
   *  source silently dropped out of interest accrual on the way (it reads PAID),
   *  so the carried balance quietly stopped accruing.
   *
   *  Only while the target is still unissued. Once it has been issued the
   *  balance is on a real, numbered note the tenant has been sent, and unwinding
   *  it behind their back is not an edit — void that note instead.
   */
  async unwindCarryForward(input: { organizationId: string; lineId: string; reversedByUserId?: string | null }): Promise<void> {
    await this.prisma.$transaction(async (tx) => {
      const line = await tx.invoiceLine.findFirst({
        where: { id: input.lineId, kind: 'OVERDUE_CARRYFORWARD', invoice: { organizationId: input.organizationId } },
        include: { invoice: { select: { id: true, status: true, billingPeriod: true } } },
      });
      if (!line) throw new NotFoundException('Carried-forward line not found');
      if (!EDITABLE.includes(line.invoice.status)) {
        throw new BadRequestException('This debit note is issued or approved; void it instead of unwinding the balance brought forward');
      }
      if (!line.sourceInvoiceId) throw new BadRequestException('This line does not record where the balance came from');

      // The transfer entry is the one posted against the target for this source.
      const entry = await tx.journalEntry.findFirst({
        where: {
          organizationId: input.organizationId,
          sourceType: 'ADJUSTMENT',
          sourceId: line.invoice.id,
          reversesId: null,
          lines: { some: { invoiceId: line.sourceInvoiceId } },
        },
        orderBy: { createdAt: 'desc' },
      });
      if (!entry) throw new BadRequestException('No ledger posting found for this carried-forward balance');

      await this.ledger.reverse(tx, {
        entryId: entry.id,
        entryDate: new Date(),
        memo: `Unwound carry-forward onto ${line.invoice.billingPeriod}`,
        createdById: input.reversedByUserId ?? null,
      });
      await tx.invoiceLine.delete({ where: { id: line.id } });

      // Both ends re-derive from the ledger, so neither can be left asserting a
      // balance the journal disagrees with.
      const src = await invoiceArState(tx, input.organizationId, line.sourceInvoiceId);
      await tx.invoice.update({
        where: { id: line.sourceInvoiceId },
        data: { status: deriveInvoiceStatus(src), note: null },
      });
      await this.restartApproval(tx, input.organizationId, line.invoice.id);
    });
  }

  private nextPeriod(period: string): string {
    const [y, m] = period.split('-').map(Number);
    const d = new Date(Date.UTC(y, m, 1)); // m is 1-based, so month index m is the next month
    return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
  }

  /** Utility charge lines from meter readings that are due and not yet billed.
   *
   * Utilities are billed in arrears: a note for August charges what was consumed
   * *before* August began, so the window is every reading that ended before this
   * period starts and has not been billed before, however old. Anything read
   * since the last note is therefore swept up rather than silently skipped, while
   * consumption still running inside this period waits for the next note — the
   * August note goes out on the 1st and cannot bill usage up to the 11th.
   *
   * A reading is only billed if the lease has a charge rule for the meter's
   * charge type — no rule, no metered line, ever.
   *
   * A master meter's usage is reduced by the usage of the sub-meters deducted
   * from it — their readings around the master's dates, matched as
   * metering/sub-meter-deduction.ts describes — and the remainder is re-priced
   * from the tariff. Deduction is in usage, not money: the tariff's fixed charge
   * is carried once by the master, and subtracting it once per sub-meter would
   * undercharge by more the more sub-meters there are. A master waits — and
   * stays in the queue — until every one of its sub-meters has been read up to
   * about its date, because billing the whole master to the residual tenant is
   * an overcharge to unwind, while waiting is an under-collection the arrears
   * sweep repairs by itself. What is left is divided between the units the meter
   * covers by their shares, and each unit's part goes on the note that bills the
   * unit — so one meter can be billed on several notes, each claiming its own. */
  private async utilityLinesForPeriod(
    organizationId: string,
    /** Which metered charge types this note may bill, and for which of the billed
     * units — derived from the lease's charge rules by expandPeriod. */
    metered: ReadonlyMap<string, string[]>,
    period: string,
    /** Whose note this is, and from when — a reading that opens before this
     * tenancy may be measuring the tenant before it. */
    tenancy: { tenantId: string; startDate: Date },
    /** Treat shares already billed on this note as available — a rebuild has to
     * reclaim its own, without stealing another note's. */
    reclaimFor?: string,
  ): Promise<{ lines: UtilityLine[]; claims: ReadingClaim[] }> {
    if (metered.size === 0) return { lines: [], claims: [] };
    const [y, mo] = period.split('-').map(Number);
    const periodStart = new Date(Date.UTC(y, mo - 1, 1));
    // A unit's share is billable here while no other note has claimed it.
    const unclaimed = (unitId: string) => ({
      claims: { none: { unitId, ...(reclaimFor ? { invoiceId: { not: reclaimFor } } : {}) } },
    });
    const readings = await this.prisma.meterReading.findMany({
      where: {
        meter: { isActive: true },
        // Filtered in the query, not after it, so an unauthorised reading never
        // reaches markReadingsBilled and cannot be staked as billed: a reading
        // qualifies through one of this note's units that has a share of the
        // meter and that no other note has billed.
        OR: [...metered].flatMap(([chargeTypeId, units]) =>
          units.map((unitId) => ({ meter: { chargeTypeId, units: { some: { unitId, share: { gt: 0 } } } }, ...unclaimed(unitId) })),
        ),
        periodEnd: { lt: periodStart },
        grossAmount: { not: null },
        // A tenant's own declaration is not billable until someone has checked
        // it against the dial photo. Staff-entered readings arrive CONFIRMED.
        status: 'CONFIRMED',
      },
      orderBy: { periodEnd: 'asc' },
      include: {
        claims: { select: { unitId: true, invoiceId: true } },
        meter: {
          include: {
            chargeType: { select: { id: true, nameEn: true } },
            // Every covered unit, not only the billed ones: a unit's part is its
            // share of all the meter's shares, or billing one unit of a
            // three-unit meter would charge it the whole amount. The units'
            // property is also what decides the rate a master is re-priced at.
            units: { include: { unit: { select: { name: true, propertyId: true } } } },
            subMeters: { where: { isActive: true }, select: { id: true, serialNo: true, units: { select: { unit: { select: { propertyId: true } } } } } },
          },
        },
      },
    });

    // One batched lookup for every sub-meter reading that could be deducted.
    const deductions = await loadDeductionContext(
      this.prisma,
      organizationId,
      readings.filter((r) => r.meter.subMeters.length > 0).map((r) => ({ ...r, subMeterIds: r.meter.subMeters.map((sm) => sm.id) })),
    );

    // A master is re-priced at its utility's rate in the property it and its
    // sub-meters are in, so only masters need a tariff here; the rest carry
    // their priced gross.
    const propertyOfMeter = (r: (typeof readings)[number]) => masterPropertyId(r.meter);
    const tariffs = await loadTariffs(
      this.prisma,
      readings.filter((r) => r.meter.subMeters.length > 0).map((r) => ({ chargeTypeId: r.meter.chargeTypeId, propertyId: propertyOfMeter(r) })),
    );

    // Utilities are billed in arrears with no lower bound, so a reading that was
    // never billed keeps waiting and lands on whatever note is raised next. Once
    // the unit changes hands that is the wrong note: the meter did not stop at
    // the handover, and the new tenant would be charged for the old one's usage.
    // Only look it up when a reading actually predates the tenancy, which is the
    // uncommon case.
    const predating = readings.filter((r) => r.periodStart.getTime() < tenancy.startDate.getTime());
    const priorTenancies = predating.length
      ? await tenanciesForUnits(this.prisma, [...new Set(predating.flatMap((r) => r.meter.units.map((mu) => mu.unitId)))])
      : [];

    const lines: UtilityLine[] = [];
    const claims: ReadingClaim[] = [];
    for (const r of readings) {
      let gross = new Decimal(r.grossAmount!.toString());
      let netUsage = new Decimal(r.readingEnd.toString()).minus(r.readingStart.toString());
      let deductionNote: string | null = null;

      if (r.meter.subMeters.length > 0) {
        const tariff = tariffFor(tariffs, r.meter.chargeTypeId, propertyOfMeter(r));
        if (!tariff) continue; // no tariff to re-price the remainder with — leave it queued
        const deduction = subMeterDeduction(r, r.meter.subMeters, deductions);
        // A sub-meter not yet read up to about this date, or deductions
        // exceeding the master, means the data is not ready. Skipping leaves the
        // reading unbilled and unclaimed, and the arrears sweep has no lower
        // bound, so it lands on a later note once the readings are in.
        if (!deduction.ready) continue;
        netUsage = netUsage.minus(deduction.used);
        if (netUsage.isNegative()) continue;
        gross = priceUsage(tariff, netUsage);
        deductionNote = deduction.parts.join(' ');
      }

      // The units this note bills, out of everything the meter covers: its own,
      // given a share, not billed by another note, and — for a reading that opens
      // before this tenancy — not someone else's at the time.
      const allowed = metered.get(r.meter.chargeTypeId) ?? [];
      const elsewhere = new Set(r.claims.filter((c) => c.invoiceId !== reclaimFor).map((c) => c.unitId));
      const billable = (unitId: string) =>
        allowed.includes(unitId) &&
        !elsewhere.has(unitId) &&
        !(r.periodStart.getTime() < tenancy.startDate.getTime() && heldByAnotherTenant(priorTenancies, [unitId], r.periodStart, tenancy.tenantId));
      // In name order, numbers by value: units billed together (614, 615 …) sit
      // side by side, so a note's share comes out whole and the odd cent of the
      // rounding falls in the same place every time.
      const covered = [...r.meter.units].sort(
        (a, b) => a.unit.name.localeCompare(b.unit.name, undefined, { numeric: true }) || a.unitId.localeCompare(b.unitId),
      );
      const shares = covered.map((mu) => new Decimal(mu.share.toString()));
      const total = sum(shares);
      if (!total.gt(0)) continue;

      // Cumulative rounding over the full coverage, by share: each unit's amount
      // is the difference of running rounded cumulative parts, so the parts add
      // up to the gross across every note that bills them — no lost or gained
      // penny.
      let prevRounded = new Decimal(0);
      let runningShare = new Decimal(0);
      for (const [i, mu] of covered.entries()) {
        runningShare = runningShare.plus(shares[i]);
        const cumRounded = toCents(gross.times(runningShare).dividedBy(total));
        const amount = cumRounded.minus(prevRounded);
        prevRounded = cumRounded;
        if (!shares[i].gt(0) || !billable(mu.unitId)) continue;
        // Claimed even when its part rounds to nothing, so the reading reads as
        // billed in full once its other units are.
        claims.push({ readingId: r.id, unitId: mu.unitId });
        if (amount.isZero()) continue;
        const part = sharePart(shares, i);
        lines.push({
          chargeTypeId: r.meter.chargeTypeId,
          description: `${r.meter.chargeType.nameEn} · ${mu.unit.name} (${r.readingStart}→${r.readingEnd}${part ? ` ${part}` : ''})`,
          amount: amount.toFixed(2),
          periodStart: r.periodStart,
          periodEnd: r.periodEnd,
          meta: {
            meterReadingId: r.id,
            meterId: r.meterId,
            serialNo: r.meter.serialNo,
            unitId: mu.unitId,
            unitName: mu.unit.name,
            readingStart: r.readingStart.toString(),
            readingEnd: r.readingEnd.toString(),
            usage: netUsage.toString(),
            unitCount: covered.length,
            share: shares[i].toString(),
            totalShare: total.toString(),
            grossAmount: gross.toFixed(2),
            ...(deductionNote ? { deductionNote } : {}),
          },
        });
      }
    }
    return { lines, claims };
  }

  private computeDueDate(period: string, leaseDueDay: number | null): Date {
    const [y, m] = period.split('-').map(Number);
    const daysInMonth = new Date(Date.UTC(y, m, 0)).getUTCDate();
    const day = Math.min(leaseDueDay ?? 10, daysInMonth);
    return new Date(Date.UTC(y, m - 1, day));
  }
}
