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

/**
 * The single authoritative billing engine. Expands a lease's charge rules into
 * invoice line specs for one monthly billing period. Pure and deterministic —
 * no DB, no framework, no float — so it can be unit-tested exhaustively and
 * reused by the manual, scheduled and preview code paths alike (the legacy
 * system had 4–6 divergent copies of this logic).
 */

export type BillingTiming = 'ADVANCE' | 'ARREARS';
export type ProrationPolicy = 'DAILY' | 'FULL_MONTH';

export interface EngineChargeRule {
  chargeTypeId: string;
  label: string; // human name for the line description
  amount: Decimal.Value;
  frequencyMonths: number;
  timing: BillingTiming;
  proration: ProrationPolicy;
  firstInvoiceOnly: boolean;
  /** Whether a lease's rent-free window waives this charge. Configuration on the
   * CHARGE TYPE, never a hardcoded 'RENT' code: the owner's rule is that a
   * rent-free period frees the rent only, while management fee, rates and
   * government rent stay payable — and the next tenancy may draw that line
   * somewhere else without a redeploy. */
  waivedDuringRentFree: boolean;
  startDate?: Date | null;
  endDate?: Date | null;
  sortOrder: number;
  /** Carried onto the lines the rule yields — a following rule's stretch names
   *  the standard figures that took effect with it (standard-billing.ts). */
  meta?: { standardChanged?: string[] };
}

export interface EngineLease {
  startDate: Date;
  endDate: Date;
  /** The one rent-free window this tenancy was signed with — a fit-out period,
   * or free months at signing. Both dates or neither; only the days it shares
   * with a line's own coverage are freed. */
  rentFreeFrom?: Date | null;
  rentFreeTo?: Date | null;
}

/** Why a line is short, carried onto the invoice line so the printed debit note
 * (and any later audit) can show the arithmetic rather than just a smaller
 * number. Days are the clipped ones — what this line actually gave away. */
export interface RentFreeMeta {
  from: string; // YYYY-MM-DD, clipped to this line's coverage
  to: string;
  days: number; // free days inside this line's coverage
  billedDays: number; // days actually charged, out of totalDays
  totalDays: number; // the occurrence's full window (1 month, or N for N-monthly)
}

export interface LineSpec {
  chargeTypeId: string;
  description: string;
  amount: string; // 2dp string, ready for DECIMAL(14,2)
  periodStart: Date;
  periodEnd: Date;
  sortOrder: number;
  meta?: { rentFree?: RentFreeMeta; standardChanged?: string[] };
}

export interface ExpandInput {
  lease: EngineLease;
  rules: EngineChargeRule[];
  period: string; // "YYYY-MM"
  isFirstInvoice: boolean;
}

const DAY_MS = 86_400_000;

function parsePeriod(period: string): { year: number; month: number } {
  const m = /^(\d{4})-(\d{2})$/.exec(period);
  if (!m) throw new Error(`Invalid billing period "${period}", expected YYYY-MM`);
  return { year: Number(m[1]), month: Number(m[2]) };
}

/** All dates handled in UTC to keep day counts stable across time zones. */
function monthStart(period: string): Date {
  const { year, month } = parsePeriod(period);
  return new Date(Date.UTC(year, month - 1, 1));
}
function monthStartOf(period: string): Date {
  return monthStart(period);
}
/** Last day of the window that spans `months` months starting at `period`.
 * months=1 → the period's own month end; months=3 → end of the 3rd month. */
function windowEnd(period: string, months: number): Date {
  const { year, month } = parsePeriod(period);
  return new Date(Date.UTC(year, month - 1 + months, 0));
}
function monthsSinceStart(leaseStart: Date, period: string): number {
  const { year, month } = parsePeriod(period);
  return (year - leaseStart.getUTCFullYear()) * 12 + (month - 1 - leaseStart.getUTCMonth());
}
function maxDate(...ds: Date[]): Date {
  return ds.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));
}
function minDate(...ds: Date[]): Date {
  return ds.reduce((a, b) => (b.getTime() < a.getTime() ? b : a));
}
function inclusiveDays(start: Date, end: Date): number {
  return Math.round((end.getTime() - start.getTime()) / DAY_MS) + 1;
}
/** The days two inclusive windows share, and where they overlap — null when
 * they don't touch. Used to take a rent-free window off a line's coverage. */
function overlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): { start: Date; end: Date; days: number } | null {
  const start = maxDate(aStart, bStart);
  const end = minDate(aEnd, bEnd);
  if (end.getTime() < start.getTime()) return null;
  return { start, end, days: inclusiveDays(start, end) };
}
function fmt(d: Date): string {
  return d.toISOString().slice(0, 10);
}

function appliesThisPeriod(rule: EngineChargeRule, lease: EngineLease, input: ExpandInput): boolean {
  if (rule.firstInvoiceOnly) return input.isFirstInvoice;
  if (rule.frequencyMonths < 1) return false; // non-recurring + not first-invoice ⇒ never
  const since = monthsSinceStart(lease.startDate, input.period);
  if (since < 0) return false; // period precedes the lease
  return since % rule.frequencyMonths === 0;
}

export function expandChargeRules(input: ExpandInput): LineSpec[] {
  const winStart = monthStartOf(input.period);
  const lines: LineSpec[] = [];

  for (const rule of [...input.rules].sort((a, b) => a.sortOrder - b.sortOrder)) {
    if (!appliesThisPeriod(rule, input.lease, input)) continue;

    // A charge billed every N months covers an N-month window; `amount` is the
    // amount for that whole occurrence, so DAILY proration must divide by the
    // window's total days — not a single month's — or multi-month charges are
    // severely under-billed on a partial first/last period.
    const windowMonths = Math.max(1, rule.frequencyMonths);
    const winEnd = windowEnd(input.period, windowMonths);
    const totalDays = inclusiveDays(winStart, winEnd);

    // Coverage window = intersection of the billing window, lease term and rule window.
    const covStart = maxDate(winStart, input.lease.startDate, rule.startDate ?? winStart);
    const covEnd = minDate(winEnd, input.lease.endDate, rule.endDate ?? winEnd);
    if (covEnd.getTime() < covStart.getTime()) continue;

    const coverageDays = inclusiveDays(covStart, covEnd);

    // Rent-free: the days this line covers that the lease's rent-free window
    // also covers are given away. Only for a charge type flagged as waived, and
    // never for a deposit or other first-invoice-only charge — those are signing
    // money, not rent for a period, so a fit-out window does not touch them.
    const free =
      rule.waivedDuringRentFree && !rule.firstInvoiceOnly && input.lease.rentFreeFrom && input.lease.rentFreeTo
        ? overlap(covStart, covEnd, input.lease.rentFreeFrom, input.lease.rentFreeTo)
        : null;
    const freeDays = free?.days ?? 0;
    // Every covered day is free ⇒ no line at all, rather than a zero one: a
    // debit note that lists "Rent 0.00" reads as a mistake, and a zero line
    // posts nothing to the ledger anyway.
    if (freeDays >= coverageDays) continue;

    // What the occurrence is billed for, in days out of `totalDays`. DAILY
    // already charges only the days it covers; FULL_MONTH charges the whole
    // occurrence however few days it covers — so the waiver takes the free days
    // off the OCCURRENCE's own daily rate (amount ÷ totalDays) in both cases.
    // That is the one divisor this engine prorates by; introducing a second
    // ("free days out of the covered days") is how the legacy system arrived at
    // two different rents for the same month.
    const baselineDays = rule.proration === 'DAILY' ? coverageDays : totalDays;
    const billedDays = baselineDays - freeDays;

    const base = new Decimal(rule.amount);
    let amount = billedDays < totalDays ? base.times(billedDays).div(totalDays) : base;
    amount = toCents(amount);
    if (amount.isZero()) continue;

    const prorated = rule.proration === 'DAILY' && coverageDays < totalDays;
    const description =
      (prorated ? `${rule.label} (${fmt(covStart)} → ${fmt(covEnd)})` : `${rule.label} · ${input.period}`) +
      (free ? ` — rent-free ${fmt(free.start)} → ${fmt(free.end)} (${freeDays} day(s) not charged)` : '');

    lines.push({
      chargeTypeId: rule.chargeTypeId,
      description,
      amount: amount.toFixed(2),
      periodStart: covStart,
      periodEnd: covEnd,
      sortOrder: rule.sortOrder,
      ...(free || rule.meta
        ? { meta: { ...rule.meta, ...(free ? { rentFree: { from: fmt(free.start), to: fmt(free.end), days: freeDays, billedDays, totalDays } } : {}) } }
        : {}),
    });
  }

  return lines;
}
