import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
import type { InvoiceStatus, Prisma, PrismaClient, ProrationPolicy } from '@prisma/client';
import { hkToday, parseDay } from '../common/hk-date';
import {
  allInForceOn,
  classifyPair,
  dayBefore,
  inForceOn,
  isInForce,
  opensAnOccurrence,
  type ChargeScope,
  type LeaseRuleRow,
  type StandardChargeRow,
} from './standard-charge.resolution';
import { buildingOf, propertiesOf } from '../common/lease-premises';
import { followedFigureOn } from './standard-billing';

/**
 * Standard charges: what a recurring charge costs at an address, and what
 * changing it means for the tenancies already running.
 *
 * Everything that decides something lives here — the routers validate input and
 * delegate — so the lease form's prefill, the rate review and the smoke that
 * proves them all reach the same answer through the same code.
 *
 * The one rule worth stating at the top: recording a new standard charge NEVER
 * edits a lease. A tenancy's charges are its own contract; the system lists what
 * a change would touch and a person decides. `applyToLeases` is that decision
 * being carried out, and it reuses the charge rule's existing date window —
 * close the old rule the day before, open a new one from the effective date —
 * rather than inventing a second way to express a stepped amount.
 */

type Db = Prisma.TransactionClient;

const fmtDay = (d: Date): string => d.toISOString().slice(0, 10);

const chargeRowSelect = {
  id: true,
  unitId: true,
  chargeTypeId: true,
  amount: true,
  effectiveFrom: true,
  note: true,
  recordedByUserId: true,
  createdAt: true,
} as const;

type DbChargeRow = { amount: Prisma.Decimal } & Omit<StandardChargeRow, 'amount'> & {
  note: string | null;
  recordedByUserId: string | null;
};

/** DECIMAL(14,2) comes back as a Prisma.Decimal; the resolution module works on
 *  2dp strings so it stays free of Prisma's types. */
const toRow = (r: DbChargeRow): StandardChargeRow & { note: string | null; recordedByUserId: string | null } => ({
  id: r.id,
  unitId: r.unitId,
  chargeTypeId: r.chargeTypeId,
  amount: r.amount.toFixed(2),
  effectiveFrom: r.effectiveFrom,
  createdAt: r.createdAt,
  note: r.note,
  recordedByUserId: r.recordedByUserId,
});

/** Every figure ever recorded for a property, its units included. Resolution
 *  needs the whole history — "in force on D" is a question about all of it — and
 *  a property's history is small enough to answer in one query. */
export async function loadHistory(db: Db, organizationId: string, propertyId: string) {
  const rows = await db.standardCharge.findMany({
    where: { organizationId, propertyId },
    orderBy: [{ effectiveFrom: 'desc' }, { createdAt: 'desc' }],
    select: chargeRowSelect,
  });
  return rows.map(toRow);
}

/** The figures a tenancy's units resolve against, each unit its own property's:
 *  a lease can take units from several purchases of a building, and one
 *  purchase's own figure says nothing of another's units. A unit that is not
 *  among `unitIds` — or none at all, for a lease that names no unit — resolves
 *  against nothing. */
export async function loadUnitHistories(
  db: Db,
  organizationId: string,
  unitIds: readonly string[],
): Promise<(unitId: string | null) => ReturnType<typeof toRow>[]> {
  const units = await db.unit.findMany({ where: { id: { in: [...unitIds] }, property: { organizationId } }, select: { id: true, propertyId: true } });
  const histories = new Map<string, ReturnType<typeof toRow>[]>();
  for (const propertyId of new Set(units.map((u) => u.propertyId))) histories.set(propertyId, await loadHistory(db, organizationId, propertyId));
  const propertyOf = new Map(units.map((u) => [u.id, u.propertyId]));
  return (unitId) => (unitId ? histories.get(propertyOf.get(unitId) ?? '') : undefined) ?? [];
}

/** The property, checked against the caller's organisation. */
async function requireProperty(db: Db, organizationId: string, propertyId: string) {
  const p = await db.property.findFirst({
    where: { id: propertyId, organizationId, deletedAt: null },
    select: { id: true, name: true },
  });
  if (!p) throw new NotFoundException('Property not found');
  return p;
}

/** The unit, checked against that property — an id from another building would
 *  otherwise store happily and resolve for nobody. */
async function requireUnitOnProperty(db: Db, propertyId: string, unitId: string) {
  const u = await db.unit.findFirst({ where: { id: unitId, propertyId, deletedAt: null }, select: { id: true, name: true } });
  if (!u) throw new BadRequestException('Unit is not on this property');
  return u;
}

/** A standard amount only means anything for a charge that recurs: a deposit or
 *  a one-off has no "monthly figure" to prefill or to step. Matched on the
 *  category, never on a code — the office adds its own recurring charges. */
async function requireRecurringChargeType(db: Db, organizationId: string, chargeTypeId: string) {
  const c = await db.chargeType.findFirst({ where: { id: chargeTypeId, organizationId }, select: { id: true, category: true } });
  if (!c) throw new BadRequestException('Charge type not found');
  if (c.category !== 'RECURRING') throw new BadRequestException('Only a recurring charge can have a standard amount');
  return c;
}

export interface RecordStandardChargeInput {
  organizationId: string;
  propertyId: string;
  unitId: string | null;
  chargeTypeId: string;
  amount: string;
  effectiveFrom: Date;
  note: string | null;
  recordedByUserId: string | null;
}

/** Records a new figure. Deliberately not an upsert: a change is a new row, and
 *  two rows for the same scope, type and date would be two answers to one
 *  question, so that is refused rather than merged. */
export async function recordStandardCharge(db: Db, input: RecordStandardChargeInput): Promise<{ id: string }> {
  await requireProperty(db, input.organizationId, input.propertyId);
  if (input.unitId) await requireUnitOnProperty(db, input.propertyId, input.unitId);
  await requireRecurringChargeType(db, input.organizationId, input.chargeTypeId);
  await assertNoDuplicate(db, input.organizationId, input.propertyId, input.unitId, input.chargeTypeId, input.effectiveFrom, null);
  const row = await db.standardCharge.create({
    data: {
      organizationId: input.organizationId,
      propertyId: input.propertyId,
      unitId: input.unitId,
      chargeTypeId: input.chargeTypeId,
      amount: input.amount,
      effectiveFrom: input.effectiveFrom,
      note: input.note,
      recordedByUserId: input.recordedByUserId,
    },
    select: { id: true },
  });
  return row;
}

/** There is no unique index to lean on — MySQL counts NULLs as distinct, so one
 *  would police the per-unit rows and wave every property-level duplicate
 *  through. This is the check that actually holds. */
async function assertNoDuplicate(
  db: Db,
  organizationId: string,
  propertyId: string,
  unitId: string | null,
  chargeTypeId: string,
  effectiveFrom: Date,
  exceptId: string | null,
): Promise<void> {
  const clash = await db.standardCharge.findFirst({
    where: {
      organizationId,
      propertyId,
      unitId,
      chargeTypeId,
      effectiveFrom,
      ...(exceptId ? { id: { not: exceptId } } : {}),
    },
    select: { id: true },
  });
  if (clash) throw new ConflictException('A standard charge for that scope already starts on that date');
}

/** Corrects a mistake in a recorded figure — a fat-fingered amount, the wrong
 *  date. NOT how a price changes: that is a new row, so the old one still
 *  answers "what was it in May". Neither the scope nor the charge type can move,
 *  for the same reason a reference value cannot change list: everything already
 *  resolved against this row would silently mean something else. */
export async function correctStandardCharge(
  db: Db,
  organizationId: string,
  id: string,
  patch: { amount: string; effectiveFrom: Date; note: string | null },
): Promise<void> {
  const row = await db.standardCharge.findFirst({
    where: { id, organizationId },
    select: { id: true, propertyId: true, unitId: true, chargeTypeId: true },
  });
  if (!row) throw new NotFoundException('Standard charge not found');
  await assertNoDuplicate(db, organizationId, row.propertyId, row.unitId, row.chargeTypeId, patch.effectiveFrom, row.id);
  await db.standardCharge.update({ where: { id: row.id }, data: patch });
}

/** Removes a figure recorded by mistake. Charge rules already applied to a
 *  tenancy stay: they are that tenancy's own terms now, agreed and possibly
 *  billed, and un-writing them from here would change money nobody asked to
 *  change. A notice that announced this row keeps its own record and loses only
 *  the link (SET NULL). */
export async function removeStandardCharge(db: Db, organizationId: string, id: string): Promise<void> {
  const claimed = await db.standardCharge.deleteMany({ where: { id, organizationId } });
  if (claimed.count !== 1) throw new NotFoundException('Standard charge not found');
}

// ─────────────────────────────────────────────────────────────────────────────
// Lease prefill
// ─────────────────────────────────────────────────────────────────────────────

export interface PrefilledRule {
  chargeTypeId: string;
  chargeTypeCode: string;
  chargeTypeNameEn: string;
  chargeTypeNameZh: string | null;
  unitId: string | null;
  unitName: string | null;
  amount: string;
  frequencyMonths: number;
  timing: 'ADVANCE';
  proration: 'DAILY';
  firstInvoiceOnly: false;
  /** A prefilled charge follows the standard from then on. */
  followsStandard: true;
  standardChargeId: string;
  scope: ChargeScope;
  effectiveFrom: string;
}

/**
 * What the charge-rule editor is offered for a tenancy starting on `onDate`.
 *
 * One rule PER UNIT: a per-unit rule bills that unit its own amount, and it is
 * the only shape a split debit note can carry (a whole-lease rule is apportioned
 * by unit count instead). Each unit is offered its own property's figures — the
 * units may come from several purchases of the building. No unit, no offer.
 *
 * Monthly, in advance, prorated daily — the shape a user would have typed, and
 * editable exactly like one. NOTHING is forced: this returns a suggestion, and
 * the lease is saved from whatever the user leaves on the form.
 */
export async function prefillForLease(
  db: Db,
  organizationId: string,
  unitIds: readonly string[],
  onDate: Date,
): Promise<PrefilledRule[]> {
  const historyOf = await loadUnitHistories(db, organizationId, unitIds);
  // Only this organisation's live units — an id from elsewhere is quietly
  // dropped rather than prefilled against the wrong building.
  const units = await db.unit.findMany({
    where: { id: { in: [...unitIds] }, property: { organizationId }, deletedAt: null },
    select: { id: true, name: true },
  });
  const history = units.flatMap((u) => historyOf(u.id));
  if (history.length === 0) return [];
  // Active only. A figure may outlive the charge type it was recorded for, but
  // the lease form's own picker offers active types only — a prefilled row for
  // a retired one would land on the form with a charge nothing can name, and
  // the user could not even see what it was before deleting it.
  const chargeTypes = await db.chargeType.findMany({
    where: { id: { in: [...new Set(history.map((h) => h.chargeTypeId))] }, isActive: true },
    select: { id: true, code: true, nameEn: true, nameZh: true },
  });
  const typeById = new Map(chargeTypes.map((c) => [c.id, c]));

  const out: PrefilledRule[] = [];
  for (const scope of units.map((u) => ({ unitId: u.id, unitName: u.name }))) {
    for (const [chargeTypeId, hit] of allInForceOn(historyOf(scope.unitId), scope.unitId, onDate)) {
      const type = typeById.get(chargeTypeId);
      if (!type) continue;
      out.push({
        chargeTypeId,
        chargeTypeCode: type.code,
        chargeTypeNameEn: type.nameEn,
        chargeTypeNameZh: type.nameZh,
        unitId: scope.unitId,
        unitName: scope.unitName,
        amount: hit.row.amount,
        frequencyMonths: 1,
        timing: 'ADVANCE',
        proration: 'DAILY',
        firstInvoiceOnly: false,
        followsStandard: true,
        standardChargeId: hit.row.id,
        scope: hit.scope,
        effectiveFrom: fmtDay(hit.row.effectiveFrom),
      });
    }
  }
  return out;
}

/** What a rule following the standard charges on `onDate`, for every charge
 *  with a figure at the units' properties: per unit named, and for the whole
 *  lease (its units that have a figure, added up — null while none has one). For a screen; billing
 *  works stretch by stretch. */
export async function standardFigures(
  db: Db,
  organizationId: string,
  unitIds: readonly string[],
  onDate: Date,
): Promise<{ chargeTypeId: string; unitId: string | null; amount: string | null }[]> {
  const historyOf = await loadUnitHistories(db, organizationId, unitIds);
  const out: { chargeTypeId: string; unitId: string | null; amount: string | null }[] = [];
  for (const chargeTypeId of new Set(unitIds.flatMap((u) => historyOf(u).map((h) => h.chargeTypeId)))) {
    for (const unitId of unitIds) out.push({ chargeTypeId, unitId, amount: followedFigureOn(historyOf, chargeTypeId, [unitId], onDate) });
    out.push({ chargeTypeId, unitId: null, amount: followedFigureOn(historyOf, chargeTypeId, unitIds, onDate) });
  }
  return out;
}

/**
 * The tenancies charging `chargeTypeId` at a price of their own where the
 * property has a standard figure for it: the current and coming rules of running
 * and upcoming leases that do not follow the standard, each beside what the
 * standard would charge (on `on`, or the rule's start if later). The rules the
 * follow-standard migration left alone, and any agreed apart since.
 */
export async function rulesNotFollowing(db: Db, organizationId: string, chargeTypeId: string, on: Date) {
  const rules = await db.chargeRule.findMany({
    where: {
      chargeTypeId,
      followsStandard: false,
      firstInvoiceOnly: false,
      frequencyMonths: { gte: 1 },
      OR: [{ endDate: null }, { endDate: { gte: on } }],
      lease: { organizationId, deletedAt: null, status: { in: ['ACTIVE', 'DRAFT'] } },
    },
    orderBy: [{ lease: { reference: 'asc' } }, { sortOrder: 'asc' }],
    select: {
      id: true,
      unitId: true,
      amount: true,
      startDate: true,
      lease: {
        select: {
          id: true,
          reference: true,
          status: true,
          startDate: true,
          tenant: { select: { name: true } },
          units: { select: { unitId: true, unit: { select: { property: { select: { id: true, name: true } } } } } },
        },
      },
    },
  });
  const historyOf = await loadUnitHistories(db, organizationId, [...new Set(rules.flatMap((r) => r.lease.units.map((u) => u.unitId)))]);
  const ofType = (unitId: string | null) => historyOf(unitId).filter((h) => h.chargeTypeId === chargeTypeId);
  const unitNames = new Map(
    (await db.unit.findMany({ where: { id: { in: rules.map((r) => r.unitId).filter((v): v is string => !!v) } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]),
  );
  return rules
    .map((r) => ({ r, units: r.unitId ? [r.unitId] : r.lease.units.map((u) => u.unitId) }))
    .filter(({ units }) => units.some((u) => ofType(u).length > 0))
    .map(({ r, units }) => {
      const start = r.startDate ?? r.lease.startDate;
      return {
        ruleId: r.id,
        leaseId: r.lease.id,
        leaseReference: r.lease.reference,
        leaseStatus: r.lease.status,
        tenantName: r.lease.tenant.name,
        propertyName: buildingOf(propertiesOf(r.lease.units)),
        /** Null: the rule is for the whole lease. */
        unitName: r.unitId ? unitNames.get(r.unitId) ?? null : null,
        amount: r.amount.toFixed(2),
        standardNow: followedFigureOn(ofType, chargeTypeId, units, start > on ? start : on),
      };
    });
}

// ─────────────────────────────────────────────────────────────────────────────
// The rate review
// ─────────────────────────────────────────────────────────────────────────────

export type BlockedReason = 'WHOLE_MONTH_MID_MONTH';
export type SkipReason = 'ALREADY_AT_NEW_AMOUNT' | 'NOT_CHARGED_ON_THIS_LEASE' | 'CHARGED_FOR_THE_WHOLE_LEASE' | 'FOLLOWS_STANDARD';

export interface AffectedLease {
  leaseId: string;
  leaseReference: string;
  tenantName: string;
  unitId: string | null;
  unitName: string | null;
  chargeRuleId: string;
  currentAmount: string;
  newAmount: string;
  effectiveFrom: string;
  frequencyMonths: number;
  proration: ProrationPolicy;
  /** How applying would be written: a second rule from the effective date, or
   *  the amount replaced where the rule has not started billing yet. */
  mode: ApplyMode;
  /** Set when applying would be refused, so the screen can grey the tick rather
   *  than let staff find out on submit. */
  blockedReason: BlockedReason | null;
}

export interface SkippedLease {
  leaseId: string;
  leaseReference: string;
  tenantName: string;
  unitId: string | null;
  unitName: string | null;
  currentAmount: string | null;
  reason: SkipReason;
}

export type ApplyMode = 'STEPPED' | 'AMENDED_IN_PLACE';

const leaseForReview = {
  id: true,
  reference: true,
  startDate: true,
  endDate: true,
  terminatedAt: true,
  tenant: { select: { name: true } },
  units: { select: { unitId: true, unit: { select: { name: true, propertyId: true } } } },
  chargeRules: {
    select: {
      id: true,
      chargeTypeId: true,
      unitId: true,
      amount: true,
      frequencyMonths: true,
      proration: true,
      startDate: true,
      endDate: true,
      sortOrder: true,
      followsStandard: true,
    },
  },
} as const;

type ReviewLease = Prisma.LeaseGetPayload<{ select: typeof leaseForReview }>;

const asRuleRows = (l: ReviewLease): LeaseRuleRow[] =>
  l.chargeRules.map((r) => ({
    id: r.id,
    chargeTypeId: r.chargeTypeId,
    unitId: r.unitId,
    amount: r.amount.toFixed(2),
    startDate: r.startDate,
    endDate: r.endDate,
    sortOrder: r.sortOrder,
  }));

/** Where this rule actually starts billing inside this tenancy: its own start
 *  date if it has one, otherwise the lease's, and never before the lease's. */
const ruleStartsAt = (rule: LeaseRuleRow, leaseStart: Date): Date =>
  rule.startDate && rule.startDate.getTime() > leaseStart.getTime() ? rule.startDate : leaseStart;

/** A rule that has not begun billing by the effective date is amended in place —
 *  closing it "the day before" would leave a window with no days in it and a
 *  rule that bills nothing, forever. Everything else is stepped. */
const modeFor = (rule: LeaseRuleRow, leaseStart: Date, effectiveFrom: Date): ApplyMode =>
  ruleStartsAt(rule, leaseStart).getTime() >= effectiveFrom.getTime() ? 'AMENDED_IN_PLACE' : 'STEPPED';

/** Stepping a whole-month charge inside one of its billing periods would bill it
 *  TWICE: the engine charges a FULL_MONTH rule its whole amount for however few
 *  days it covers, so the closed rule and its successor would each take a full
 *  occurrence. Refused rather than silently doubled; the office dates such a
 *  change to the start of a period, which is how the notices are written anyway.
 *
 *  Measured in OCCURRENCES, not months: a quarterly whole-month charge stepped
 *  on the 1st of a month that is not the start of its quarter doubles that
 *  quarter just as surely as a mid-month step doubles a month. */
const blockedFor = (
  rule: { proration: ProrationPolicy; frequencyMonths: number },
  mode: ApplyMode,
  leaseStart: Date,
  effectiveFrom: Date,
): BlockedReason | null =>
  mode === 'STEPPED' && rule.proration === 'FULL_MONTH' && !opensAnOccurrence(leaseStart, effectiveFrom, rule.frequencyMonths)
    ? 'WHOLE_MONTH_MID_MONTH'
    : null;

export interface ReviewResult {
  standardCharge: {
    id: string;
    propertyId: string;
    propertyName: string;
    unitId: string | null;
    unitName: string | null;
    chargeTypeId: string;
    chargeTypeCode: string;
    chargeTypeNameEn: string;
    chargeTypeNameZh: string | null;
    amount: string;
    effectiveFrom: string;
    inForce: boolean;
  };
  affected: AffectedLease[];
  skipped: SkippedLease[];
}

/**
 * Which running tenancies a recorded figure actually changes, and by how much.
 *
 * WHICH LEASES ARE LOOKED AT: ACTIVE ones on that property whose term still has
 * days left on the effective date. A DRAFT is excluded — its charges are still
 * being typed, and creating it prefills from these very figures; an ENDED or
 * TERMINATED one is excluded, as is an ACTIVE one whose term (or early
 * termination) is already past on that date, because there is nothing left for
 * the new amount to bill.
 *
 * WHICH SCOPE ON EACH LEASE: exactly the scope this row is the answer for. A
 * property-level figure reaches only the units that have no figure of their own,
 * and neither reaches anything once a later row has superseded it.
 */
export async function reviewStandardCharge(db: Db, organizationId: string, standardChargeId: string): Promise<ReviewResult> {
  const row = await db.standardCharge.findFirst({
    where: { id: standardChargeId, organizationId },
    select: { ...chargeRowSelect, propertyId: true },
  });
  if (!row) throw new NotFoundException('Standard charge not found');
  const [property, chargeType, history] = await Promise.all([
    requireProperty(db, organizationId, row.propertyId),
    db.chargeType.findFirstOrThrow({ where: { id: row.chargeTypeId }, select: { id: true, code: true, nameEn: true, nameZh: true } }),
    loadHistory(db, organizationId, row.propertyId),
  ]);
  const effectiveFrom = row.effectiveFrom;
  const amount = row.amount.toFixed(2);
  const scopeUnit = row.unitId
    ? await db.unit.findFirst({ where: { id: row.unitId }, select: { id: true, name: true } })
    : null;

  const leases = await db.lease.findMany({
    where: {
      organizationId,
      units: { some: { unit: { propertyId: row.propertyId } } },
      deletedAt: null,
      status: 'ACTIVE',
      endDate: { gte: effectiveFrom },
      OR: [{ terminatedAt: null }, { terminatedAt: { gte: effectiveFrom } }],
    },
    orderBy: { reference: 'asc' },
    select: leaseForReview,
  });

  const affected: AffectedLease[] = [];
  const skipped: SkippedLease[] = [];

  for (const lease of leases) {
    const rules = asRuleRows(lease);
    // The scopes on this lease that THIS row is the answer for — among the
    // units on this property: a lease may take others from another purchase.
    const leaseUnits = lease.units.filter((u) => u.unit.propertyId === row.propertyId).map((u) => ({ unitId: u.unitId, unitName: u.unit.name }));
    const candidates: { unitId: string | null; unitName: string | null }[] = row.unitId
      ? leaseUnits.filter((u) => u.unitId === row.unitId)
      : leaseUnits.length
        ? leaseUnits
        : [{ unitId: null, unitName: null }];

    // A whole-lease rule is the answer for every unit on the tenancy, so it must
    // be reported ONCE however many units resolve to it.
    const reportedWholeLeaseRules = new Set<string>();

    for (const scope of candidates) {
      if (inForceOn(history, row.chargeTypeId, scope.unitId, effectiveFrom)?.row.id !== row.id) continue;
      const outcome = classifyPair(rules, row.chargeTypeId, scope.unitId, effectiveFrom, amount);
      const common = {
        leaseId: lease.id,
        leaseReference: lease.reference,
        tenantName: lease.tenant.name,
        unitId: scope.unitId,
        unitName: scope.unitName,
      };
      if (outcome.kind === 'NOT_CHARGED_ON_THIS_LEASE') {
        skipped.push({ ...common, currentAmount: null, reason: 'NOT_CHARGED_ON_THIS_LEASE' });
        continue;
      }
      // A rule following the standard takes the new figure by itself, from its
      // effective date: nothing to apply. Reported once, like a whole-lease rule.
      if (lease.chargeRules.find((r) => r.id === outcome.rule.id)?.followsStandard) {
        if (reportedWholeLeaseRules.has(outcome.rule.id)) continue;
        reportedWholeLeaseRules.add(outcome.rule.id);
        const wholeLease = outcome.rule.unitId === null;
        skipped.push({
          ...common,
          ...(wholeLease ? { unitId: null, unitName: null } : {}),
          currentAmount: null,
          reason: 'FOLLOWS_STANDARD',
        });
        continue;
      }
      // The unit is billed by a rule bound to no unit: that amount is the
      // tenancy's TOTAL for the charge — apportioned across the billed units by
      // unit count on a split note — not this unit's figure, so it is not
      // comparable to a per-unit standard amount and stepping it would silently
      // reprice every other unit on the lease. It is also the SAME rule for each
      // of them, so offered per unit it would be closed and succeeded once per
      // unit. Reported, never offered: changing it is a lease amendment, made on
      // the lease form.
      if (scope.unitId !== null && outcome.rule.unitId === null) {
        if (reportedWholeLeaseRules.has(outcome.rule.id)) continue;
        reportedWholeLeaseRules.add(outcome.rule.id);
        skipped.push({
          ...common,
          unitId: null,
          unitName: null,
          currentAmount: outcome.rule.amount,
          reason: 'CHARGED_FOR_THE_WHOLE_LEASE',
        });
        continue;
      }
      if (outcome.kind === 'ALREADY_AT_NEW_AMOUNT') {
        skipped.push({ ...common, currentAmount: outcome.rule.amount, reason: 'ALREADY_AT_NEW_AMOUNT' });
        continue;
      }
      const dbRule = lease.chargeRules.find((r) => r.id === outcome.rule.id)!;
      const mode = modeFor(outcome.rule, lease.startDate, effectiveFrom);
      affected.push({
        ...common,
        chargeRuleId: outcome.rule.id,
        currentAmount: outcome.rule.amount,
        newAmount: amount,
        effectiveFrom: fmtDay(effectiveFrom),
        frequencyMonths: dbRule.frequencyMonths,
        proration: dbRule.proration,
        mode,
        blockedReason: blockedFor(dbRule, mode, lease.startDate, effectiveFrom),
      });
    }
  }

  return {
    standardCharge: {
      id: row.id,
      propertyId: row.propertyId,
      propertyName: property.name,
      unitId: row.unitId,
      unitName: scopeUnit?.name ?? null,
      chargeTypeId: chargeType.id,
      chargeTypeCode: chargeType.code,
      chargeTypeNameEn: chargeType.nameEn,
      chargeTypeNameZh: chargeType.nameZh,
      amount,
      effectiveFrom: fmtDay(effectiveFrom),
      inForce: isInForce(history, toRow(row), hkToday()),
    },
    affected,
    skipped,
  };
}

export interface ApplyTarget {
  leaseId: string;
  unitId: string | null;
}

export interface AppliedLease {
  leaseId: string;
  leaseReference: string;
  unitId: string | null;
  closedRuleId: string;
  newRuleId: string | null;
  mode: ApplyMode;
  previousAmount: string;
  newAmount: string;
}

export interface ApplyResult {
  applied: AppliedLease[];
  /** Debit notes not yet issued whose period ends on or after the change. They
   *  still show the OLD amount until they are rebuilt — nothing here touches a
   *  note, issued or draft — so the screen can say which ones to rebuild. The
   *  status comes with them because only a DRAFT or in-approval note can be
   *  rebuilt; an approved one has to be voided and raised again. */
  draftInvoices: { id: string; number: string | null; billingPeriod: string; status: InvoiceStatus; leaseId: string; leaseReference: string }[];
}

/**
 * Carries the decision out on the ticked tenancies.
 *
 * The mechanism is the charge rule's existing date window, not a new field:
 * the rule in force is closed at the day before the effective date and a second
 * rule takes over from the effective date with the new amount, keeping the
 * original's frequency, timing, proration, unit and end date. Consecutive days,
 * so the two windows can neither overlap (one month billed twice) nor leave a
 * gap (a month billed at nothing). Where the rule has not begun billing yet its
 * amount is simply replaced — a closed window with no days in it would be a rule
 * that bills nothing forever.
 *
 * Nothing here touches an invoice. An issued note is history; a draft keeps the
 * figures it was built with until someone rebuilds it, and the result says which
 * drafts those are.
 */
export async function applyToLeases(
  prisma: PrismaClient,
  organizationId: string,
  standardChargeId: string,
  targets: readonly ApplyTarget[],
): Promise<ApplyResult> {
  const review = await reviewStandardCharge(prisma, organizationId, standardChargeId);
  const effectiveFrom = parseDay(review.standardCharge.effectiveFrom);
  const key = (leaseId: string, unitId: string | null): string => `${leaseId}|${unitId ?? ''}`;
  const byKey = new Map(review.affected.map((a) => [key(a.leaseId, a.unitId), a]));

  const chosen = targets.map((t) => {
    const hit = byKey.get(key(t.leaseId, t.unitId ?? null));
    // Re-derived, never trusted from the client: the list staff ticked may be
    // minutes old, and the amounts on it are money.
    if (!hit) throw new ConflictException('That lease is no longer affected by this standard charge; open the review again');
    if (hit.blockedReason === 'WHOLE_MONTH_MID_MONTH') {
      throw new BadRequestException('A charge billed by whole month can only change from the start of one of its billing periods');
    }
    return hit;
  });
  // One rule, one step. The compare-and-swap below assumes each rule is written
  // once in this transaction: run twice, the second close re-writes an endDate
  // it already holds (which MySQL counts as a matched row, so the CAS passes)
  // and a second successor is created. The review cannot produce two rows for
  // one rule — this holds that guarantee where the money is written.
  const ruleIds = chosen.map((c) => c.chargeRuleId);
  if (new Set(ruleIds).size !== ruleIds.length) throw new Error('Two ticked rows resolve to the same charge rule');

  const applied = await prisma.$transaction(async (tx) => {
    const out: AppliedLease[] = [];
    for (const target of chosen) {
      const rule = await tx.chargeRule.findFirst({ where: { id: target.chargeRuleId, leaseId: target.leaseId } });
      // Compare-and-swap on everything the decision was made from: amount, both
      // window ends and the lease it belongs to. Someone editing the lease in
      // another tab replaces its rules outright, so the row may be gone or may
      // be a different agreement wearing the same id.
      if (!rule || rule.amount.toFixed(2) !== target.currentAmount) {
        throw new ConflictException('This lease’s charges changed while you were reviewing; open the review again');
      }
      if (target.mode === 'AMENDED_IN_PLACE') {
        const claimed = await tx.chargeRule.updateMany({
          where: { id: rule.id, leaseId: target.leaseId, amount: rule.amount },
          data: { amount: target.newAmount },
        });
        if (claimed.count !== 1) throw new ConflictException('This lease’s charges changed while you were reviewing; open the review again');
        out.push({
          leaseId: target.leaseId,
          leaseReference: target.leaseReference,
          unitId: target.unitId,
          closedRuleId: rule.id,
          newRuleId: null,
          mode: 'AMENDED_IN_PLACE',
          previousAmount: target.currentAmount,
          newAmount: target.newAmount,
        });
        continue;
      }
      const closed = await tx.chargeRule.updateMany({
        where: { id: rule.id, leaseId: target.leaseId, amount: rule.amount, endDate: rule.endDate },
        data: { endDate: dayBefore(effectiveFrom) },
      });
      if (closed.count !== 1) throw new ConflictException('This lease’s charges changed while you were reviewing; open the review again');
      const created = await tx.chargeRule.create({
        data: {
          leaseId: target.leaseId,
          chargeTypeId: review.standardCharge.chargeTypeId,
          unitId: rule.unitId,
          amount: target.newAmount,
          frequencyMonths: rule.frequencyMonths,
          timing: rule.timing,
          proration: rule.proration,
          firstInvoiceOnly: rule.firstInvoiceOnly,
          startDate: effectiveFrom,
          // The successor inherits the original's end: a change of price must
          // not also extend a charge past the date it was agreed to stop.
          endDate: rule.endDate,
          // Beside its predecessor in the printed order, not at the bottom.
          sortOrder: rule.sortOrder,
          note: rule.note,
        },
        select: { id: true },
      });
      out.push({
        leaseId: target.leaseId,
        leaseReference: target.leaseReference,
        unitId: target.unitId,
        closedRuleId: rule.id,
        newRuleId: created.id,
        mode: 'STEPPED',
        previousAmount: target.currentAmount,
        newAmount: target.newAmount,
      });
    }
    return out;
  });

  const leaseIds = [...new Set(applied.map((a) => a.leaseId))];
  const drafts = leaseIds.length
    ? await prisma.invoice.findMany({
        where: {
          organizationId,
          leaseId: { in: leaseIds },
          status: { in: ['DRAFT', 'PENDING_APPROVAL', 'APPROVED'] },
          // A note is affected when the days it COVERS reach the change, not
          // when its period LABEL does: a charge billed every N months is
          // labelled with the first month of its window, so a quarterly note
          // "2026-10" runs to 2026-12-31 and a change from 2026-11-01 does
          // change it when it is rebuilt. The label compare still catches a note
          // that has no lines to go by ("YYYY-MM" sorts lexicographically, so a
          // string compare is the calendar compare). An ISSUED note is history
          // and is never listed, whatever its period.
          OR: [
            { lines: { some: { periodEnd: { gte: effectiveFrom } } } },
            { billingPeriod: { gte: fmtDay(effectiveFrom).slice(0, 7) } },
          ],
        },
        orderBy: { billingPeriod: 'asc' },
        select: { id: true, number: true, billingPeriod: true, status: true, leaseId: true, lease: { select: { reference: true } } },
      })
    : [];

  return {
    applied,
    draftInvoices: drafts.map((d) => ({
      id: d.id,
      number: d.number,
      billingPeriod: d.billingPeriod,
      status: d.status,
      leaseId: d.leaseId,
      leaseReference: d.lease.reference,
    })),
  };
}

/** Used by the list screen: what each scope actually pays on a date, after
 *  unit-beats-property, alongside the raw history. */
export interface EffectiveFigure {
  unitId: string | null;
  chargeTypeId: string;
  amount: string;
  standardChargeId: string;
  scope: ChargeScope;
}

export function effectiveFigures(
  history: readonly StandardChargeRow[],
  unitIds: readonly string[],
  onDate: Date,
): EffectiveFigure[] {
  const out: EffectiveFigure[] = [];
  for (const unitId of [null, ...unitIds]) {
    for (const [chargeTypeId, hit] of allInForceOn(history, unitId, onDate)) {
      out.push({ unitId, chargeTypeId, amount: hit.row.amount, standardChargeId: hit.row.id, scope: hit.scope });
    }
  }
  return out;
}
