import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import type { MeterReading, Prisma, UtilityTariff } from '@prisma/client';
import { Decimal } from '@rms/domain';
import { PrismaService } from '../prisma/prisma.service';
import { loadDeductionContext, subMeterDeduction } from './sub-meter-deduction';
import { loadTariffs, masterPropertyId, meterPropertyId, priceUsage, tariffFor } from './tariff';
import { heldByAnotherTenant, tenanciesForUnits } from './tenancy';

/** Why a confirmed reading has not reached a debit note yet. Billing skips such
 *  a reading in silence — correctly, since the alternative is billing something
 *  wrong — so the list has to be able to say which of these it is. Null means
 *  nothing is holding it: the next note for that lease will carry it. */
export type ReadingBlock =
  | 'AWAITING_REVIEW'
  | 'REJECTED'
  | 'METER_INACTIVE'
  | 'METER_SPANS_PROPERTIES'
  | 'NO_TARIFF'
  | 'WAITING_SUB_METER'
  | 'SUB_EXCEEDS_MASTER'
  | 'NO_LEASE'
  | 'PREVIOUS_TENANT'
  | 'NO_CHARGE_RULE'
  | 'NOT_DUE_YET';

/** A reading's block, and for a master waiting on its sub-meters, which ones and
 *  how far they need reading — "a sub-meter" is no help on a building with ten. */
export interface ReadingHold {
  code: ReadingBlock;
  waitingFor?: { serialNo: string | null; units: string[] }[];
  /** Each sub-meter in waitingFor needs a reading ending on or after this day. */
  readBy?: Date;
}

interface ReadingFields {
  readingStart: string;
  readingEnd: string;
  periodStart: string;
  periodEnd: string;
  note?: string | null;
}

@Injectable()
export class MeteringService {
  constructor(private readonly prisma: PrismaService) {}

  /** Prices a reading's gross from the tariff of the property its meter is in:
   *  gross = (end − start) × unitRate + fixedCharge.
   *  Billing later divides this evenly between the units the meter covers. For a
   *  master meter it re-prices instead, from the usage left after its sub-meters
   *  are deducted — so this figure is the un-deducted one.
   *
   *  With no tariff the gross is left null — unpriced, not zero. A zero is
   *  skipped by billing without ever being marked billed, and would still be
   *  zero once the property's rate was set; null keeps the reading out of
   *  billing until priceUnpriced gives it a real amount. */
  private price(tariff: UtilityTariff | null, input: ReadingFields) {
    const start = new Decimal(input.readingStart);
    const end = new Decimal(input.readingEnd);
    if (end.lt(start)) throw new BadRequestException('End reading must be greater than or equal to start');
    return {
      readingStart: start.toFixed(3),
      readingEnd: end.toFixed(3),
      periodStart: new Date(input.periodStart),
      periodEnd: new Date(input.periodEnd),
      grossAmount: tariff ? priceUsage(tariff, end.minus(start)).toFixed(2) : null,
    };
  }

  /** The tariff a meter's readings are priced from: its utility's rate in the
   *  property the meter is in. */
  private async tariffOfMeter(meter: { chargeTypeId: string; units: { unit: { propertyId: string } }[] }): Promise<UtilityTariff | null> {
    const propertyId = meterPropertyId(meter.units.map((mu) => mu.unit.propertyId));
    return tariffFor(await loadTariffs(this.prisma, [{ chargeTypeId: meter.chargeTypeId, propertyId }]), meter.chargeTypeId, propertyId);
  }

  /** Two confirmed readings covering the same days on one meter bill the same
   *  units twice: billing takes every confirmed, priced, unclaimed reading whose
   *  period has closed and makes a line of each — utilityLinesForPeriod has no
   *  overlap test, and nothing behind it has one either. It is easy to get there
   *  without noticing, because the office form and the tenant's own form both
   *  open from the last CONFIRMED figure: a declaration still waiting to be
   *  checked and a reading the office walks out and takes can cover the same
   *  stretch. Refused where the figures are written, the way the rest of this
   *  codebase makes an invalid state unrepresentable rather than detectable.
   *
   *  Only CONFIRMED rows are in the way. A declaration awaiting review is a
   *  claim, not a fact, and a sent-back one is a number already judged wrong —
   *  neither can reach a note. That leaves the order of work free: the office
   *  can record its own reading first and send the superseded declaration back
   *  afterwards, and it is confirming the second of two overlapping declarations
   *  that is refused, never the first.
   *
   *  Touching dates pass: readings chain end to end, so this period's start IS
   *  last period's end. Only days genuinely covered twice are refused. */
  private async assertNoOverlap(meterId: string, input: ReadingFields, exceptId?: string): Promise<void> {
    const clash = await this.prisma.meterReading.findFirst({
      where: {
        meterId,
        status: 'CONFIRMED',
        ...(exceptId ? { id: { not: exceptId } } : {}),
        periodStart: { lt: new Date(input.periodEnd) },
        periodEnd: { gt: new Date(input.periodStart) },
      },
      select: { id: true },
    });
    if (clash) {
      throw new ConflictException('This meter already has a confirmed reading covering those dates, so the same usage would be billed twice; correct or send back one of them first.');
    }
  }

  async createReading(input: { organizationId: string; meterId: string } & ReadingFields): Promise<MeterReading> {
    // Scope the meter by org (through any covered unit) so a reading can't be
    // created against another org's meter.
    const meter = await this.prisma.meter.findFirst({
      where: { id: input.meterId, units: { some: { unit: { property: { organizationId: input.organizationId } } } } },
      select: { chargeTypeId: true, units: { select: { unit: { select: { propertyId: true } } } } },
    });
    if (!meter) throw new NotFoundException('Meter not found');
    // A reading the office enters arrives CONFIRMED, so it is billable the moment
    // it exists — the overlap has to be caught before the row, not after.
    await this.assertNoOverlap(input.meterId, input);
    const row = await this.prisma.meterReading.create({
      data: { meterId: input.meterId, ...this.price(await this.tariffOfMeter(meter), input), note: input.note ?? null },
    });
    return this.recheckUnpriced(row);
  }

  /** A confirmed reading written with no rate looks again once it has committed.
   *  A rate saved between this write's lookup and the write itself was followed
   *  by a scan that could not see this reading yet, so without this it would
   *  wait for a rate that already exists. */
  private async recheckUnpriced(row: MeterReading): Promise<MeterReading> {
    if (row.grossAmount !== null || row.status !== 'CONFIRMED') return row;
    await this.priceUnpriced({ id: row.meterId });
    return this.prisma.meterReading.findUniqueOrThrow({ where: { id: row.id } });
  }

  /** Re-prices and updates a reading against its meter's current tariff. Issued
   *  invoices froze the old amounts at billing time, so this changes the reading
   *  record and any future drafts — not invoices that were already issued.
   *
   *  Which is exactly why a reading already ON a note cannot be edited. The
   *  frozen amount is only half of what that note says: the printed debit note
   *  carries an evidence page that re-reads the reading LIVE (document.service
   *  evidencePages), so a corrected dial would show new figures beside a charge
   *  computed from the old ones — the tenant downloads a PDF that contradicts
   *  itself. Refused here rather than in the router, because this is the one
   *  place a reading's figures are written; deleteReading refuses the same thing
   *  for the same note, in the router where its own write lives.
   *
   *  confirmReading comes through here too and is unaffected: a declaration
   *  awaiting review has never been billed (billing takes CONFIRMED readings
   *  only), so it can still be corrected against the photo and accepted. */
  async updateReading(input: { organizationId: string; id: string } & ReadingFields): Promise<MeterReading> {
    const reading = await this.prisma.meterReading.findFirst({
      where: { id: input.id, meter: { units: { some: { unit: { property: { organizationId: input.organizationId } } } } } },
      include: {
        meter: { select: { chargeTypeId: true, units: { select: { unit: { select: { propertyId: true } } } } } },
        _count: { select: { claims: true } },
      },
    });
    if (!reading) throw new NotFoundException('Reading not found');
    if (reading._count.claims > 0) {
      // Only two things let go of the claim: voiding the note (releaseReadings),
      // or taking the reading's own line off a note still in draft. "Rebuild"
      // looks like a third and is not — regenerateDraft releases and re-stakes
      // the same claim inside one transaction — so the message must not send
      // anyone there.
      throw new ConflictException(
        'This reading is already billed on a debit note; void that note, or remove its metered line while the note is still a draft. Rebuilding the note re-claims the same reading.',
      );
    }
    // Confirming a declaration comes through here while the row is still PENDING,
    // so this is also the check on the way to CONFIRMED: a declaration that
    // covers days the office has since read itself is refused, and the answer is
    // to send it back.
    await this.assertNoOverlap(reading.meterId, input, reading.id);
    const row = await this.prisma.meterReading.update({
      where: { id: input.id },
      // Only overwrite note when the caller sent one, so a re-price doesn't wipe it.
      data: { ...this.price(await this.tariffOfMeter(reading.meter), input), ...(input.note !== undefined ? { note: input.note } : {}) },
    });
    return this.recheckUnpriced(row);
  }

  /** Gives an amount to every reading on the matched meters that is still
   *  waiting for a rate, from the tariff each meter resolves to now. Run when a
   *  property's rate is set, when a meter's units change (which can put it in a
   *  property that has one), and when a reading is written or confirmed with no
   *  rate.
   *
   *  Always once the caller's change has committed, never inside its
   *  transaction: a rate and a reading saved at the same moment cannot see each
   *  other from inside either one, so each side looks again after its own write
   *  and whichever looks last sees both. Looking twice is harmless — only a
   *  reading still without an amount is written.
   *
   *  Only confirmed, unbilled readings with no amount. A declaration is priced
   *  when it is confirmed, and an amount once set stays what it was: changing a
   *  rate is not retrospective. */
  async priceUnpriced(meters: Prisma.MeterWhereInput): Promise<void> {
    const readings = await this.prisma.meterReading.findMany({
      where: { grossAmount: null, status: 'CONFIRMED', claims: { none: {} }, meter: meters },
      select: {
        id: true,
        readingStart: true,
        readingEnd: true,
        meter: { select: { chargeTypeId: true, units: { select: { unit: { select: { propertyId: true } } } } } },
      },
    });
    if (readings.length === 0) return;
    const located = readings.map((r) => ({
      ...r,
      chargeTypeId: r.meter.chargeTypeId,
      propertyId: meterPropertyId(r.meter.units.map((mu) => mu.unit.propertyId)),
    }));
    const tariffs = await loadTariffs(this.prisma, located);
    for (const r of located) {
      const tariff = tariffFor(tariffs, r.chargeTypeId, r.propertyId);
      if (!tariff) continue;
      const usage = new Decimal(r.readingEnd.toString()).minus(r.readingStart.toString());
      // Conditional on the figures that were priced, so a reading billed or
      // corrected in the meantime is not given an amount for usage it no longer
      // has; a corrected one is priced by its own write's second look.
      await this.prisma.meterReading.updateMany({
        where: { id: r.id, grossAmount: null, claims: { none: {} }, readingStart: r.readingStart, readingEnd: r.readingEnd },
        data: { grossAmount: priceUsage(tariff, usage).toFixed(2) },
      });
    }
  }

  /** Sets one property's rate for a utility, and prices the readings there that
   *  were waiting for it. */
  async setTariff(input: { organizationId: string; chargeTypeId: string; propertyId: string; unitRate: string; fixedCharge: string }): Promise<void> {
    const { chargeTypeId, propertyId, unitRate, fixedCharge } = input;
    await this.assertTariffScope(input.organizationId, chargeTypeId, propertyId);
    await this.prisma.utilityTariff.upsert({
      where: { chargeTypeId_propertyId: { chargeTypeId, propertyId } },
      update: { unitRate, fixedCharge },
      create: { chargeTypeId, propertyId, unitRate, fixedCharge },
    });
    // After the rate has committed (see priceUnpriced). Every meter touching the
    // property; a legacy one that also spans another resolves to no property and
    // is left unpriced by the resolution itself.
    await this.priceUnpriced({ chargeTypeId, units: { some: { unit: { propertyId } } } });
  }

  /** Removes one property's rate for a utility. Readings keep the amounts they
   *  were already priced at; new ones there stay unpriced until a rate is set. */
  async clearTariff(input: { organizationId: string; chargeTypeId: string; propertyId: string }): Promise<void> {
    await this.assertTariffScope(input.organizationId, input.chargeTypeId, input.propertyId);
    await this.prisma.utilityTariff.deleteMany({ where: { chargeTypeId: input.chargeTypeId, propertyId: input.propertyId } });
  }

  /** A rate is for a UTILITY charge type and a live property, both in the
   *  caller's organisation — the tariff row has no organisation of its own to
   *  be scoped by. */
  private async assertTariffScope(organizationId: string, chargeTypeId: string, propertyId: string): Promise<void> {
    const [chargeType, property] = await Promise.all([
      this.prisma.chargeType.findFirst({ where: { id: chargeTypeId, organizationId, category: 'UTILITY' }, select: { id: true } }),
      this.prisma.property.findFirst({ where: { id: propertyId, organizationId, deletedAt: null }, select: { id: true } }),
    ]);
    if (!chargeType) throw new BadRequestException('Utility charge type not found');
    if (!property) throw new NotFoundException('Property not found');
  }

  /** For each reading not yet billed in full, what is holding back the units
   *  still unbilled — mirroring exactly the conditions billing filters on, so
   *  the answer here is the reason there. A reading whose every unit with a
   *  share is on a note is not waiting, and is not examined.
   *
   *  `asOf` is the day to judge "not due yet" against: utilities bill in arrears,
   *  so a reading is only swept up by a note whose period starts after the
   *  reading's period ended. */
  async explainUnbilled(
    organizationId: string,
    readings: readonly {
      id: string;
      meterId: string;
      periodStart: Date;
      periodEnd: Date;
      readingStart: Prisma.Decimal;
      readingEnd: Prisma.Decimal;
      grossAmount: Prisma.Decimal | null;
      status: string;
      /** The units already billed, one per claim. */
      claims: readonly { unitId: string }[];
    }[],
    asOf: Date,
  ): Promise<Map<string, ReadingHold>> {
    const out = new Map<string, ReadingHold>();
    if (readings.length === 0) return out;

    const meters = await this.prisma.meter.findMany({
      where: { id: { in: [...new Set(readings.map((r) => r.meterId))] } },
      select: {
        id: true,
        isActive: true,
        chargeTypeId: true,
        units: { select: { unitId: true, share: true, unit: { select: { propertyId: true } } } },
        subMeters: {
          where: { isActive: true },
          select: { id: true, serialNo: true, units: { select: { unit: { select: { propertyId: true, name: true } } } } },
        },
      },
    });
    const meterById = new Map(meters.map((m) => [m.id, m]));
    // The units each reading still has to bill: those with a share and no claim.
    const unbilledUnits = (r: (typeof readings)[number]) =>
      (meterById.get(r.meterId)?.units ?? [])
        .filter((u) => Number(u.share) > 0 && !r.claims.some((c) => c.unitId === u.unitId))
        .map((u) => u.unitId);
    const pending = readings.filter((r) => unbilledUnits(r).length > 0);
    if (pending.length === 0) return out;

    // The property each meter is billed in, resolved the way billing resolves
    // it; only a master is re-priced there, so only masters need today's rate.
    const propertyOf = new Map(meters.map((m) => [m.id, masterPropertyId(m)]));
    const tariffs = await loadTariffs(
      this.prisma,
      meters.filter((m) => m.subMeters.length > 0).map((m) => ({ chargeTypeId: m.chargeTypeId, propertyId: propertyOf.get(m.id) ?? null })),
    );

    // Sub-meter readings matched the way billing matches them, so "waiting on a
    // sub-meter" is answered by the same rule billing applies.
    const deductions = await loadDeductionContext(
      this.prisma,
      organizationId,
      pending.flatMap((r) => {
        const subMeterIds = meterById.get(r.meterId)?.subMeters.map((sm) => sm.id) ?? [];
        return subMeterIds.length ? [{ ...r, subMeterIds }] : [];
      }),
    );

    // The tenancy that would be billed, and whether it is contracted for this
    // utility at all — a charge rule for the meter's charge type is what
    // authorises a metered charge, exactly as in billing.
    const allUnitIds = [...new Set(meters.flatMap((m) => m.units.map((u) => u.unitId)))];
    const leases = await this.prisma.lease.findMany({
      where: { organizationId, deletedAt: null, status: { in: ['ACTIVE', 'TERMINATED'] }, units: { some: { unitId: { in: allUnitIds } } } },
      select: { tenantId: true, startDate: true, units: { select: { unitId: true } }, chargeRules: { select: { chargeTypeId: true, unitId: true } } },
    });
    const tenancies = await tenanciesForUnits(this.prisma, allUnitIds);

    // Arrears: a note for month M carries readings whose period ended before M
    // began, so anything ending this month or later is simply not due yet.
    const thisMonthStart = new Date(Date.UTC(asOf.getUTCFullYear(), asOf.getUTCMonth(), 1));

    for (const r of pending) {
      if (r.status === 'PENDING') { out.set(r.id, { code: 'AWAITING_REVIEW' }); continue; }
      if (r.status === 'REJECTED') { out.set(r.id, { code: 'REJECTED' }); continue; }

      const m = meterById.get(r.meterId);
      if (!m) continue;
      if (!m.isActive) { out.set(r.id, { code: 'METER_INACTIVE' }); continue; }
      // Billing's own test: an unpriced reading never reaches it, and a priced
      // one bills at its stored amount whatever the rate is now — except a
      // master, which is re-priced and so needs a rate today.
      const propertyId = propertyOf.get(m.id) ?? null;
      if (r.grossAmount === null || (m.subMeters.length > 0 && !tariffFor(tariffs, m.chargeTypeId, propertyId))) {
        out.set(r.id, { code: propertyId === null ? 'METER_SPANS_PROPERTIES' : 'NO_TARIFF' });
        continue;
      }

      // Only the units not billed yet: the rest are on their notes already.
      const unitIds = unbilledUnits(r);

      if (m.subMeters.length > 0) {
        const deduction = subMeterDeduction(r, m.subMeters, deductions);
        if (!deduction.ready) {
          const waitingFor = m.subMeters
            .filter((sm) => deduction.waitingFor.includes(sm.id))
            .map((sm) => ({ serialNo: sm.serialNo, units: sm.units.map((u) => u.unit.name) }));
          out.set(r.id, { code: 'WAITING_SUB_METER', waitingFor, readBy: deduction.readBy });
          continue;
        }
        const own = new Decimal(r.readingEnd.toString()).minus(r.readingStart.toString());
        if (own.minus(deduction.used).isNegative()) { out.set(r.id, { code: 'SUB_EXCEEDS_MASTER' }); continue; }
      }

      const covering = leases.filter((l) => l.units.some((u) => unitIds.includes(u.unitId)));
      if (covering.length === 0) { out.set(r.id, { code: 'NO_LEASE' }); continue; }

      // Whichever tenancy would actually be billed — the one that has started.
      const billable = covering.filter(
        (l) => !(r.periodStart.getTime() < l.startDate.getTime() && heldByAnotherTenant(tenancies, unitIds, r.periodStart, l.tenantId)),
      );
      if (billable.length === 0) { out.set(r.id, { code: 'PREVIOUS_TENANT' }); continue; }

      const authorised = billable.some((l) =>
        l.chargeRules.some((cr) => cr.chargeTypeId === m.chargeTypeId && (cr.unitId === null || unitIds.includes(cr.unitId))),
      );
      if (!authorised) { out.set(r.id, { code: 'NO_CHARGE_RULE' }); continue; }

      if (r.periodEnd.getTime() >= thisMonthStart.getTime()) { out.set(r.id, { code: 'NOT_DUE_YET' }); continue; }
      // Nothing is holding it: the next note for this lease will carry it.
    }
    return out;
  }
}
