import type { Prisma } from '@prisma/client';
import { Decimal } from '@rms/domain';

/*
 * How much of a master meter's usage its sub-meters take off.
 *
 * The master is the power company's meter, read on the company's own billing
 * dates; the sub-meters are the office's, photographed by staff or tenants on
 * whatever day suits. Their windows never line up exactly, and they do not need
 * to: the dials are cumulative, so a sub-meter reading that runs a few days past
 * the bill is simply that much less next time. What has to hold is that every
 * sub-meter reading is deducted from exactly one master reading — so over time
 * the deductions add up to the sub-meter's whole usage — and that a master is
 * not billed before each of its sub-meters has been read up to about its date.
 *
 * A sub-meter reading belongs to the master reading its end date falls in,
 * shifted by the tolerance: (previous master end + tolerance, master end +
 * tolerance]. Bounded by the previous reading's END, not this one's start, so
 * the windows tile however the dates were typed — "1 Sep – 30 Sep, 1 Oct – 31
 * Oct" leaves a day between the two that a start-bounded window would drop.
 * Billing and explainUnbilled both decide through here, so a reading the list
 * says is ready is one billing will take.
 */

export const SUB_METER_TOLERANCE_KEY = 'metering.sub_meter_tolerance_days';
export const DEFAULT_SUB_METER_TOLERANCE_DAYS = 7;
const DAY_MS = 86_400_000;

/** How many days either side of the master's date a sub-meter reading may fall
 *  and still count for that bill. The default when unset or not a whole number
 *  of days up to a month. */
export async function loadSubMeterTolerance(db: Pick<Prisma.TransactionClient, 'setting'>, organizationId: string): Promise<number> {
  const row = await db.setting.findFirst({ where: { organizationId, key: SUB_METER_TOLERANCE_KEY }, select: { value: true } });
  const v = row?.value;
  const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
  return Number.isInteger(n) && n >= 0 && n <= 31 ? n : DEFAULT_SUB_METER_TOLERANCE_DAYS;
}

type SubReading = { meterId: string; periodEnd: Date; readingStart: Prisma.Decimal; readingEnd: Prisma.Decimal };

type MasterReading = { id: string; meterId: string; periodStart: Date; periodEnd: Date };

export interface DeductionContext {
  toleranceDays: number;
  subReadings: readonly SubReading[];
  /** Each master reading's lower bound: where the reading before it ended. */
  windowFrom: ReadonlyMap<string, number>;
}

/** Everything subMeterDeduction needs for these master readings, in three
 *  queries however many there are. */
export async function loadDeductionContext(
  db: Pick<Prisma.TransactionClient, 'setting' | 'meterReading'>,
  organizationId: string,
  masters: readonly (MasterReading & { subMeterIds: readonly string[] })[],
): Promise<DeductionContext> {
  if (masters.length === 0) return { toleranceDays: DEFAULT_SUB_METER_TOLERANCE_DAYS, subReadings: [], windowFrom: new Map() };
  const toleranceDays = await loadSubMeterTolerance(db, organizationId);
  const tol = toleranceDays * DAY_MS;

  // The confirmed reading before each one on the same master. Without one — the
  // master's first — the day before its own start stands in.
  const earlier = await db.meterReading.findMany({
    where: {
      meterId: { in: [...new Set(masters.map((m) => m.meterId))] },
      status: 'CONFIRMED',
      periodEnd: { lt: new Date(Math.max(...masters.map((m) => m.periodEnd.getTime()))) },
    },
    select: { meterId: true, periodEnd: true },
  });
  const windowFrom = new Map(
    masters.map((m) => {
      const prev = earlier
        .filter((e) => e.meterId === m.meterId && e.periodEnd.getTime() < m.periodEnd.getTime())
        .reduce((max, e) => Math.max(max, e.periodEnd.getTime()), -Infinity);
      return [m.id, (Number.isFinite(prev) ? prev : m.periodStart.getTime() - DAY_MS) + tol] as const;
    }),
  );

  // Low enough for both questions asked of them: which fall in a window, and
  // whether a sub-meter has been read up to about a master's date.
  const from = Math.min(...masters.map((m) => Math.min(windowFrom.get(m.id)!, m.periodEnd.getTime() - tol)));
  const subMeterIds = [...new Set(masters.flatMap((m) => m.subMeterIds))];
  const subReadings = subMeterIds.length
    ? await db.meterReading.findMany({
        where: { meterId: { in: subMeterIds }, status: 'CONFIRMED', periodEnd: { gte: new Date(from) } },
        select: { meterId: true, periodEnd: true, readingStart: true, readingEnd: true },
      })
    : [];
  return { toleranceDays, subReadings, windowFrom };
}

export type SubMeterDeduction =
  /** These sub-meters have not been read up to about the master's date yet:
   *  each needs a reading ending on or after `readBy`. */
  | { ready: false; waitingFor: string[]; readBy: Date }
  | { ready: true; used: Decimal; parts: string[] };

/** The usage this master reading's sub-meters take off it. */
export function subMeterDeduction(
  master: MasterReading,
  subMeters: readonly { id: string; serialNo?: string | null }[],
  ctx: DeductionContext,
): SubMeterDeduction {
  const tol = ctx.toleranceDays * DAY_MS;
  const from = ctx.windowFrom.get(master.id) ?? master.periodStart.getTime() - DAY_MS + tol;
  const to = master.periodEnd.getTime() + tol;
  const readUpTo = master.periodEnd.getTime() - tol;
  let used = new Decimal(0);
  const parts: string[] = [];
  const waitingFor: string[] = [];
  for (const sm of subMeters) {
    const own = ctx.subReadings.filter((r) => r.meterId === sm.id);
    // Not read up to about the bill's date: what it takes off this bill is not
    // known yet, and billing the master whole would overcharge its tenant.
    // Every such sub-meter is named, so whoever goes to read them goes once.
    if (!own.some((r) => r.periodEnd.getTime() >= readUpTo)) {
      waitingFor.push(sm.id);
      continue;
    }
    // Read only well past the date: nothing falls in this window, and the whole
    // of that reading comes off the next bill instead.
    const smUsed = own
      .filter((r) => r.periodEnd.getTime() > from && r.periodEnd.getTime() <= to)
      .reduce((acc, r) => acc.plus(new Decimal(r.readingEnd.toString()).minus(r.readingStart.toString())), new Decimal(0));
    used = used.plus(smUsed);
    parts.push(`- ${smUsed.toString()} (${sm.serialNo ?? 'sub-meter'})`);
  }
  if (waitingFor.length) return { ready: false, waitingFor, readBy: new Date(readUpTo) };
  return { ready: true, used, parts };
}
