import { Decimal } from '@rms/domain';

/**
 * The two questions standard charges have to answer, as pure functions:
 *
 *   1. "What is the management fee at this address on this date?" — resolution
 *      over the history of recorded figures.
 *   2. "This tenancy is charging X; the standard is now Y — is it affected?" —
 *      the comparison a rate review is made of.
 *
 * Both are here rather than in a query, because both are decisions the office
 * has to be able to reproduce on paper, and because a wrong answer to either is
 * money. No DB, no framework, no float — unit-tested exhaustively next door.
 */

/** One recorded figure. A change is a NEW row, never an edit of the old one. */
export interface StandardChargeRow {
  id: string;
  /** Null = the property's own figure; set = that unit's own. */
  unitId: string | null;
  chargeTypeId: string;
  amount: string; // 2dp string, as DECIMAL(14,2) reads back
  effectiveFrom: Date;
  createdAt: Date;
}

/** Which scope produced an answer, so the screen can say where it came from. */
export type ChargeScope = 'UNIT' | 'PROPERTY';

export interface Resolved<T extends StandardChargeRow = StandardChargeRow> {
  row: T;
  scope: ChargeScope;
}

const day = (d: Date): number => d.getTime();

/** Latest first: by effectiveFrom, then by when it was recorded, then by id.
 *  The last two only ever decide a tie the service refuses to create — two rows
 *  for the same scope, type and date — and exist so that even then the system
 *  gives ONE answer rather than a different one per query plan. */
function latestFirst(a: StandardChargeRow, b: StandardChargeRow): number {
  return day(b.effectiveFrom) - day(a.effectiveFrom) || day(b.createdAt) - day(a.createdAt) || (a.id < b.id ? 1 : -1);
}

/**
 * The figure in force on `on` for one unit of a property, or — with `unitId`
 * null — for the property itself.
 *
 * UNIT BEATS PROPERTY, whatever the dates. A unit that has its own figure is
 * answered by its own history alone; the property's rows are the default for
 * the units that have none. (The alternative — "whichever row is newest" — would
 * let a building-wide notice silently overwrite the one shop that negotiated its
 * own fee, which is exactly the case the office keeps a per-unit figure for.)
 *
 * Within the winning scope, the answer is the row with the greatest
 * effectiveFrom that is not in the future relative to `on`. Rows dated after
 * `on` are the announced future; they are not in force yet.
 */
export function inForceOn<T extends StandardChargeRow>(
  rows: readonly T[],
  chargeTypeId: string,
  unitId: string | null,
  on: Date,
): Resolved<T> | null {
  const started = rows.filter((r) => r.chargeTypeId === chargeTypeId && day(r.effectiveFrom) <= day(on));
  if (unitId !== null) {
    const own = started.filter((r) => r.unitId === unitId).sort(latestFirst);
    if (own.length > 0) return { row: own[0], scope: 'UNIT' };
  }
  const shared = started.filter((r) => r.unitId === null).sort(latestFirst);
  return shared.length > 0 ? { row: shared[0], scope: 'PROPERTY' } : null;
}

/** Every charge type that has an answer for this unit on `on`, keyed by type.
 *  This is what a new lease is offered and what a review compares against. */
export function allInForceOn<T extends StandardChargeRow>(
  rows: readonly T[],
  unitId: string | null,
  on: Date,
): Map<string, Resolved<T>> {
  const out = new Map<string, Resolved<T>>();
  for (const chargeTypeId of new Set(rows.map((r) => r.chargeTypeId))) {
    const hit = inForceOn(rows, chargeTypeId, unitId, on);
    if (hit) out.set(chargeTypeId, hit);
  }
  return out;
}

/** True when `row` is the one `inForceOn` would pick for its own scope — what
 *  the history list marks as current, as opposed to superseded or not yet due. */
export function isInForce(rows: readonly StandardChargeRow[], row: StandardChargeRow, on: Date): boolean {
  const hit = inForceOn(rows, row.chargeTypeId, row.unitId, on);
  return hit !== null && hit.row.id === row.id && hit.scope === (row.unitId === null ? 'PROPERTY' : 'UNIT');
}

// ─────────────────────────────────────────────────────────────────────────────
// The rate review: which tenancies a new figure actually changes.
// ─────────────────────────────────────────────────────────────────────────────

/** A lease's own charge rule, as the review reads it. */
export interface LeaseRuleRow {
  id: string;
  chargeTypeId: string;
  unitId: string | null;
  amount: string;
  startDate: Date | null;
  endDate: Date | null;
  sortOrder: number;
}

/**
 * The rule that bills `chargeTypeId` for `unitId` on `on` — the amount a tenant
 * is paying that day. A rule bound to the unit wins over a whole-lease rule, the
 * same precedence the standard charges themselves use; among equals the first in
 * the lease's own order wins, because that is the one the engine lists first.
 *
 * A rule whose window does not contain `on` is not the current amount: a stepped
 * rent that has already been closed off is history, and its successor is the
 * answer.
 */
export function ruleInForceOn(
  rules: readonly LeaseRuleRow[],
  chargeTypeId: string,
  unitId: string | null,
  on: Date,
): LeaseRuleRow | null {
  const covering = rules.filter(
    (r) =>
      r.chargeTypeId === chargeTypeId &&
      (r.startDate === null || day(r.startDate) <= day(on)) &&
      (r.endDate === null || day(r.endDate) >= day(on)),
  );
  const byOrder = (a: LeaseRuleRow, b: LeaseRuleRow): number => a.sortOrder - b.sortOrder || (a.id < b.id ? -1 : 1);
  if (unitId !== null) {
    const own = covering.filter((r) => r.unitId === unitId).sort(byOrder);
    if (own.length > 0) return own[0];
  }
  const shared = covering.filter((r) => r.unitId === null).sort(byOrder);
  return shared.length > 0 ? shared[0] : null;
}

export type PairOutcome =
  /** Charged today at a different amount — the row staff can tick. */
  | { kind: 'AFFECTED'; rule: LeaseRuleRow }
  /** Already at the new figure: applying would write the same number twice. */
  | { kind: 'ALREADY_AT_NEW_AMOUNT'; rule: LeaseRuleRow }
  /** This tenancy does not charge it at all. NOT offered: the mechanism steps an
   *  existing charge, and starting one a tenancy never agreed to is an amendment
   *  to the lease, made on the lease. Reported so the office can see it rather
   *  than wonder why the list is short. */
  | { kind: 'NOT_CHARGED_ON_THIS_LEASE' };

/** What a new standard figure means for one (lease, unit) pair. */
export function classifyPair(
  rules: readonly LeaseRuleRow[],
  chargeTypeId: string,
  unitId: string | null,
  effectiveFrom: Date,
  newAmount: string,
): PairOutcome {
  const rule = ruleInForceOn(rules, chargeTypeId, unitId, effectiveFrom);
  if (!rule) return { kind: 'NOT_CHARGED_ON_THIS_LEASE' };
  // Compared as decimals, never as strings: "500" and "500.00" are the same
  // money, and a string compare would offer a no-op change on every lease whose
  // amount happens to be stored with a different scale.
  const same = new Decimal(rule.amount).equals(new Decimal(newAmount));
  return same ? { kind: 'ALREADY_AT_NEW_AMOUNT', rule } : { kind: 'AFFECTED', rule };
}

/** The day before `d`, which is where the rule being replaced is closed off.
 *  Dates are stored as UTC midnight, so this is exact arithmetic, not a
 *  calendar guess. */
export function dayBefore(d: Date): Date {
  return new Date(d.getTime() - 86_400_000);
}

/**
 * Does `on` open one of a charge's own billing occurrences?
 *
 * A charge billed every N months is billed in the periods where
 * `monthsSinceStart(lease.startDate, period) % N === 0`, and the amount is the
 * amount for that whole N-month occurrence. So the first day of an occurrence
 * is the only place a whole-month charge can be stepped: anywhere inside one,
 * the closed rule and its successor would EACH take a full occurrence — a
 * quarter billed twice. For a monthly charge every 1st opens an occurrence,
 * which is the rule the office already writes its notices by.
 *
 * Anchored on the LEASE's start, not the rule's, because that is what the
 * billing engine aligns occurrences by.
 */
export function opensAnOccurrence(leaseStart: Date, on: Date, frequencyMonths: number): boolean {
  if (on.getUTCDate() !== 1) return false;
  const months = (on.getUTCFullYear() - leaseStart.getUTCFullYear()) * 12 + (on.getUTCMonth() - leaseStart.getUTCMonth());
  return months >= 0 && months % Math.max(1, frequencyMonths) === 0;
}
