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

/*
 * Utility rates are set per property — the same water costs a different amount
 * in different buildings — and there is no organisation-wide fallback. Every
 * place that needs a meter's rate (pricing a reading, re-pricing a master at
 * billing, explaining why a reading is stuck, the tariff editor) resolves it
 * through here, so none of them can disagree about which rate applies.
 */

/** The property whose rates price a meter: the one property every unit it
 *  covers is in. A meter is refused units in two properties, so null only
 *  happens for one that already spanned two before that rule existed. Such a
 *  meter has no rate, and its unpriced readings wait as METER_SPANS_PROPERTIES
 *  until its units are corrected. */
export function meterPropertyId(unitPropertyIds: readonly string[]): string | null {
  const distinct = new Set(unitPropertyIds);
  return distinct.size === 1 ? [...distinct][0] : null;
}

type CoveredUnits = { units: readonly { unit: { propertyId: string } }[] };

/** The property a master is re-priced in at billing: the one its own units and
 *  its active sub-meters' units are all in. The usage a sub-meter takes off the
 *  master at this rate is charged to the sub-meter's unit at its own property's,
 *  and the two only add back up when that is the same property — so a pair
 *  across two properties (only possible from before that was refused) has no
 *  rate, and waits rather than billing at two. For a meter with no sub-meters
 *  this is simply meterPropertyId. */
export function masterPropertyId(meter: CoveredUnits & { subMeters: readonly CoveredUnits[] }): string | null {
  return meterPropertyId([meter, ...meter.subMeters].flatMap((m) => m.units.map((mu) => mu.unit.propertyId)));
}

export const tariffKey = (chargeTypeId: string, propertyId: string): string => `${chargeTypeId}|${propertyId}`;

/** Every tariff a batch of (utility, property) pairs could use, in one query,
 *  keyed by tariffKey. A pair with no property is skipped — nothing prices it. */
export async function loadTariffs(
  db: Pick<Prisma.TransactionClient, 'utilityTariff'>,
  pairs: readonly { chargeTypeId: string; propertyId: string | null }[],
): Promise<Map<string, UtilityTariff>> {
  const chargeTypeIds = [...new Set(pairs.filter((p) => p.propertyId !== null).map((p) => p.chargeTypeId))];
  const propertyIds = [...new Set(pairs.map((p) => p.propertyId).filter((v): v is string => v !== null))];
  if (propertyIds.length === 0) return new Map();
  const rows = await db.utilityTariff.findMany({ where: { chargeTypeId: { in: chargeTypeIds }, propertyId: { in: propertyIds } } });
  return new Map(rows.map((t) => [tariffKey(t.chargeTypeId, t.propertyId), t]));
}

/** The rate for this utility in this property, or null when that property has
 *  not set one. */
export function tariffFor(tariffs: ReadonlyMap<string, UtilityTariff>, chargeTypeId: string, propertyId: string | null): UtilityTariff | null {
  return propertyId === null ? null : (tariffs.get(tariffKey(chargeTypeId, propertyId)) ?? null);
}

/** usage × unitRate + fixedCharge, to the cent. */
export function priceUsage(tariff: Pick<UtilityTariff, 'unitRate' | 'fixedCharge'>, usage: Decimal): Decimal {
  return toCents(usage.times(tariff.unitRate.toString()).plus(tariff.fixedCharge.toString()));
}
