import { Decimal } from '@rms/domain';
import { inForceOn, type StandardChargeRow } from './standard-charge.resolution';

/**
 * A charge rule that follows the property's standard charge
 * (ChargeRule.followsStandard), as the billing engine bills it: one stretch per
 * run of days over which the standard figure for the rule's units stays the
 * same, each billed like a rule of its own with that figure as its amount.
 *
 * The figure is the units' figures added up — one unit's for a rule bound to a
 * unit, every unit's the rule bills for a whole-lease one — each resolved as the
 * rest of the system resolves it (unit beats property, standard-charge.
 * resolution.ts). A unit with no figure yet is left out of the sum. The stretch
 * has none, and the rule's own amount is billed, only when none of its units
 * has a figure.
 *
 * A change takes effect on its effective date for a rule prorated by day, and
 * the engine splits that billing period between the two figures by days. A rule
 * billed by whole period would bill such a period twice over, once at each
 * figure, so for it a change takes effect from the start of its next billing
 * period instead (nextPeriodStart).
 *
 * Pure: no DB, no framework, no float.
 */

export interface FollowSegment {
  /** First day, inclusive. */
  start: Date;
  /** Last day, inclusive; null when open-ended. */
  end: Date | null;
  /** The figure for the stretch, as a 2dp string; null where none of the units has one. */
  amount: string | null;
  /** The recorded figures that took effect at `start` and changed what is
   *  billed — the notices behind them are what the debit note shows. Set on
   *  the first billing period of a new figure only, when `nextPeriod` is given. */
  changed: string[];
}

const DAY_MS = 86_400_000;

/** The figures a rule's units resolve against: one property's history, or each
 *  unit's 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. */
export type StandardHistory = readonly StandardChargeRow[] | ((unitId: string | null) => readonly StandardChargeRow[]);

const historyOf = (history: StandardHistory) => (typeof history === 'function' ? history : () => history);

/** The first day of a billing period, on or after `day`, of a charge billed
 *  every `months` months of a tenancy that started on `leaseStart` — periods
 *  counted from the tenancy's first month, as the engine counts them. */
export function nextPeriodStart(leaseStart: Date, months: number, day: Date): Date {
  const every = Math.max(1, months);
  const month = day.getUTCMonth() + (day.getUTCDate() === 1 ? 0 : 1);
  const since = (day.getUTCFullYear() - leaseStart.getUTCFullYear()) * 12 + (month - leaseStart.getUTCMonth());
  const off = ((since % every) + every) % every;
  return new Date(Date.UTC(day.getUTCFullYear(), month + (off === 0 ? 0 : every - off), 1));
}

/** What a following rule charges on `on`: the figures of the units that have
 *  one, added up. Null only when none of them has a figure yet — the rule's own
 *  amount is billed then. A unit with no figure is left out, not a reason to
 *  drop the others. */
export function followedFigureOn(
  history: StandardHistory,
  chargeTypeId: string,
  unitIds: readonly (string | null)[],
  on: Date,
): string | null {
  const of = historyOf(history);
  let total = new Decimal(0);
  let any = false;
  for (const unitId of unitIds) {
    const hit = inForceOn(of(unitId), chargeTypeId, unitId, on);
    if (!hit) continue;
    any = true;
    total = total.plus(hit.row.amount);
  }
  return any ? total.toFixed(2) : null;
}

export function followSegments(input: {
  history: StandardHistory;
  chargeTypeId: string;
  /** The units the rule bills; [null] for a tenancy that names none. */
  unitIds: readonly (string | null)[];
  /** The rule's first day — its own start, else the tenancy's. */
  from: Date;
  /** Its last day, or null when open-ended. */
  to: Date | null;
  /** When a figure recorded as effective on a day starts to be billed. The day
   *  itself unless given (see nextPeriodStart). */
  effectiveOn?: (day: Date) => Date;
  /** The first day of the billing period after the one `day` is in. Given,
   *  a stretch opening with a change is split there, so the change is told on
   *  the note that first bills the new figure and not on every one after. */
  nextPeriod?: (day: Date) => Date;
}): FollowSegment[] {
  const { chargeTypeId, unitIds, from, to } = input;
  const effectiveOn = input.effectiveOn ?? ((d: Date) => d);
  const of = historyOf(input.history);
  const relevant = (unitId: string | null) =>
    of(unitId).filter((r) => r.chargeTypeId === chargeTypeId && (r.unitId === null || unitIds.includes(r.unitId)));
  const rows = [...new Set(unitIds.flatMap(relevant))];

  // Where the figure can change: each recorded figure's effective date as this
  // rule takes it, inside the rule's own window. One already in force on its
  // first day is in the opening figure, not a change.
  const changesAt = new Map<number, string[]>();
  for (const r of rows) {
    const at = effectiveOn(r.effectiveFrom).getTime();
    if (at <= from.getTime() || (to && at > to.getTime())) continue;
    changesAt.set(at, [...(changesAt.get(at) ?? []), r.id]);
  }

  const segments: FollowSegment[] = [{ start: from, end: null, amount: followedFigureOn(relevant, chargeTypeId, unitIds, from), changed: [] }];
  for (const at of [...changesAt.keys()].sort((a, b) => a - b)) {
    const start = new Date(at);
    const amount = followedFigureOn(relevant, chargeTypeId, unitIds, start);
    const last = segments[segments.length - 1];
    // A figure recorded at what the units already pay changes nothing billed.
    if (amount === last.amount) continue;
    last.end = new Date(at - DAY_MS);
    // Of the figures taking effect here, the ones the units are now billed at.
    const nowBilled = new Set(unitIds.map((u) => inForceOn(relevant(u), chargeTypeId, u, start)?.row.id));
    segments.push({ start, end: null, amount, changed: changesAt.get(at)!.filter((id) => nowBilled.has(id)) });
  }
  segments[segments.length - 1].end = to;
  if (!input.nextPeriod) return segments;
  return segments.flatMap((s) => {
    if (s.changed.length === 0) return [s];
    const next = input.nextPeriod!(s.start);
    if (s.end && next.getTime() > s.end.getTime()) return [s];
    return [
      { ...s, end: new Date(next.getTime() - DAY_MS) },
      { start: next, end: s.end, amount: s.amount, changed: [] },
    ];
  });
}
