import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { Context } from '../trpc';
import { router, withPermission } from '../trpc';
import { Decimal } from '@rms/domain';
import { hkToday } from '../../common/hk-date';
import { propertyLabel } from '../../common/property-label';
import { unitsLabel } from '../../common/unit-label';
import { loadTariffs, meterPropertyId, tariffFor, tariffKey } from '../../metering/tariff';

/** The units' properties, as the select that meterPropertyId reads. */
const UNIT_PROPERTIES = { units: { select: { unit: { select: { propertyId: true } } } } } as const;
const propertyOf = (meter: { units: { unit: { propertyId: string } }[] }) => meterPropertyId(meter.units.map((mu) => mu.unit.propertyId));

/** Every unitId must belong to the caller's org. Archived units are allowed so a
 * meter that already covers a since-archived unit stays editable. */
async function assertUnitsInOrg(ctx: Pick<Context, 'prisma' | 'organizationId'>, unitIds: string[]): Promise<void> {
  const distinct = [...new Set(unitIds)];
  const n = await ctx.prisma.unit.count({
    where: { id: { in: distinct }, property: { organizationId: ctx.organizationId ?? undefined } },
  });
  if (n !== distinct.length) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Some units are not in this organization' });
}

/** A unit appears at most once on a meter; each has its own share of it
 * (checkedShares). */
function assertDistinctUnits(unitIds: string[]): void {
  if (new Set(unitIds).size !== unitIds.length) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A unit can only appear once on a meter' });
  }
}

/** Each unit's share of a meter, by unit id, as decimal text. */
const sharesInput = z.record(z.string(), z.string()).optional();

/** The shares as stored, for every unit the meter covers: a number from 0 to
 *  9999 with at most four decimals, 1 for a unit given none. Every share 0 is a
 *  meter billed to no one — a pantry's, read only to come off a master. */
function checkedShares(unitIds: readonly string[], given: Record<string, string> | undefined): Map<string, string> {
  const out = new Map<string, string>();
  for (const unitId of unitIds) {
    const raw = (given?.[unitId] ?? '1').trim();
    if (!/^\d{1,4}(\.\d{1,4})?$/.test(raw)) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'A share must be a number from 0 to 9999, with at most four decimals' });
    }
    out.set(unitId, new Decimal(raw).toString());
  }
  return out;
}

/** How far a reading is billed — not at all, for some of its units, or for
 *  every unit with a share — and on which notes. */
function billingOf(
  r: { claims: { unitId: string; invoiceId: string }[]; meter: { units: { unitId: string; share: { toString(): string }; unit: { name: string } }[] } },
  numbers: ReadonlyMap<string, string | null>,
) {
  const billable = r.meter.units.filter((mu) => new Decimal(mu.share.toString()).gt(0));
  const unbilled = billable.filter((mu) => !r.claims.some((c) => c.unitId === mu.unitId));
  return {
    billing:
      r.claims.length === 0
        ? billable.length === 0
          ? ('NOT_BILLABLE' as const) // a meter billed to no one: nothing is owed on it
          : ('NONE' as const)
        : unbilled.length === 0
          ? ('FULL' as const)
          : ('PARTIAL' as const),
    billedOn: [...new Set(r.claims.map((c) => c.invoiceId))].map((id) => ({ id, number: numbers.get(id) ?? null })),
    /** Named while some are billed and these are not. */
    unbilledUnits: r.claims.length === 0 ? [] : unbilled.map((mu) => mu.unit.name),
    /** The same, as one short label: "617–631". */
    unbilledLabel: r.claims.length === 0 ? '' : unitsLabel(unbilled.map((mu) => mu.unit.name)),
  };
}

/** A meter is priced at its property's rate, so every unit it covers must be in
 * one property. Returns that property. */
async function assertOneProperty(ctx: Pick<Context, 'prisma'>, unitIds: string[]): Promise<string> {
  const units = await ctx.prisma.unit.findMany({ where: { id: { in: unitIds } }, select: { propertyId: true } });
  const propertyId = meterPropertyId(units.map((u) => u.propertyId));
  if (!propertyId) throw new TRPCError({ code: 'BAD_REQUEST', message: 'All units on a meter must be in the same property' });
  return propertyId;
}

/** A meter deducted from a master may not itself have sub-meters, and may not be
 * its own parent. One level is all the billing needs, and refusing a second is
 * what makes a cycle impossible without walking the graph.
 *
 * It must also be in the master's property. The deduction is in usage: what a
 * sub-meter takes off the master at the master's rate is charged to its own unit
 * at its own property's rate, and the two only add back up to the master's bill
 * when that is the same rate. `propertyId` is the master's, as it will be once
 * saved. A sub-meter already deducted from this master is only held to that
 * when `recheckAttached` (the master's units are changing): re-saving a pair
 * from before the rule, unchanged, must not be refused. */
async function assertDeductible(
  ctx: { prisma: Context['prisma']; organizationId: string | null },
  meterId: string | null,
  chargeTypeId: string,
  propertyId: string | null,
  subMeterIds: string[],
  recheckAttached = true,
): Promise<void> {
  if (subMeterIds.length === 0) return;
  assertDistinctUnits(subMeterIds);
  if (meterId && subMeterIds.includes(meterId)) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A meter cannot be deducted from itself' });
  }
  const subs = await ctx.prisma.meter.findMany({
    where: { id: { in: subMeterIds }, units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined } } } } },
    select: { id: true, chargeTypeId: true, parentMeterId: true, _count: { select: { subMeters: true } }, ...UNIT_PROPERTIES },
  });
  if (subs.length !== subMeterIds.length) throw new TRPCError({ code: 'NOT_FOUND', message: 'Meter not found' });
  for (const sub of subs) {
    if (sub.chargeTypeId !== chargeTypeId) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'A sub-meter must measure the same utility as its master' });
    }
    const attached = meterId !== null && sub.parentMeterId === meterId;
    if ((!attached || recheckAttached) && (propertyId === null || propertyOf(sub) !== propertyId)) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'A sub-meter must be in the same property as its master' });
    }
    if (sub._count.subMeters > 0) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'A meter that already has sub-meters cannot be deducted from another' });
    }
    if (sub.parentMeterId && sub.parentMeterId !== meterId) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'That meter is already deducted from another master' });
    }
  }
}

/** The charge type must be a UTILITY type in the caller's org. */
async function assertUtilityChargeType(ctx: Pick<Context, 'prisma' | 'organizationId'>, chargeTypeId: string): Promise<void> {
  const ct = await ctx.prisma.chargeType.findFirst({
    where: { id: chargeTypeId, organizationId: ctx.organizationId ?? undefined, category: 'UTILITY' },
    select: { id: true },
  });
  if (!ct) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Utility charge type not found' });
}

export const meteringRouter = router({
  /** Each utility charge type with every property's rate for it, for the tariff
   *  editor. Rates are per property with no fallback, so a property without one
   *  cannot price that utility; meterCount says whether that matters there. */
  tariffs: withPermission('meter-reading.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [types, properties, meters] = await Promise.all([
      ctx.prisma.chargeType.findMany({
        where: { organizationId: org, category: 'UTILITY', isActive: true },
        orderBy: { sortOrder: 'asc' },
        select: { id: true, code: true, nameEn: true, nameZh: true },
      }),
      ctx.prisma.property.findMany({
        where: { organizationId: org, deletedAt: null },
        orderBy: [{ name: 'asc' }, { code: 'asc' }],
        select: { id: true, name: true, code: true },
      }),
      ctx.prisma.meter.findMany({
        where: { isActive: true, units: { some: { unit: { property: { organizationId: org } } } } },
        select: { chargeTypeId: true, ...UNIT_PROPERTIES },
      }),
    ]);
    const tariffs = await loadTariffs(ctx.prisma, types.flatMap((t) => properties.map((p) => ({ chargeTypeId: t.id, propertyId: p.id }))));
    // Active meters per (utility, property), by the property each resolves to.
    const meterCount = new Map<string, number>();
    for (const m of meters) {
      const propertyId = propertyOf(m);
      if (propertyId === null) continue;
      const key = tariffKey(m.chargeTypeId, propertyId);
      meterCount.set(key, (meterCount.get(key) ?? 0) + 1);
    }
    return types.map((t) => ({
      chargeTypeId: t.id,
      code: t.code,
      nameEn: t.nameEn,
      nameZh: t.nameZh,
      properties: properties.map((p) => {
        const tariff = tariffFor(tariffs, t.id, p.id);
        return {
          propertyId: p.id,
          propertyName: propertyLabel(p),
          unitRate: tariff ? tariff.unitRate.toString() : '0',
          fixedCharge: tariff ? tariff.fixedCharge.toString() : '0',
          hasTariff: tariff !== null,
          meterCount: meterCount.get(tariffKey(t.id, p.id)) ?? 0,
        };
      }),
    }));
  }),

  /** Set one property's rate for a utility. Readings there that were waiting for
   *  a rate are priced from it straight away. */
  upsertTariff: withPermission('meter-reading.update')
    .input(
      z.object({
        chargeTypeId: z.string(),
        propertyId: z.string(),
        unitRate: z.string().regex(/^\d+(\.\d{1,6})?$/),
        fixedCharge: z.string().regex(/^\d+(\.\d{1,2})?$/).default('0'),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      await ctx.metering.setTariff({ organizationId: ctx.organizationId ?? '', ...input });
      return { ok: true };
    }),

  /** Remove one property's rate for a utility. Existing readings keep their frozen amounts. */
  deleteTariff: withPermission('meter-reading.update')
    .input(z.object({ chargeTypeId: z.string(), propertyId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.metering.clearTariff({ organizationId: ctx.organizationId ?? '', ...input });
      return { ok: true };
    }),

  /** Units + utility charge types, for creating meters. */
  formData: withPermission('meter-reading.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [properties, utilityTypes] = await Promise.all([
      ctx.prisma.property.findMany({
        where: { organizationId: org, deletedAt: null },
        orderBy: [{ name: 'asc' }, { code: 'asc' }],
        select: { id: true, name: true, code: true, units: { where: { deletedAt: null }, select: { id: true, name: true } } },
      }),
      ctx.prisma.chargeType.findMany({
        where: { organizationId: org, category: 'UTILITY', isActive: true },
        orderBy: { sortOrder: 'asc' },
        select: { id: true, nameEn: true },
      }),
    ]);
    return { properties, utilityTypes };
  }),

  meters: withPermission('meter-reading.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.meter.findMany({
      where: { units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined, deletedAt: null } } } } },
      orderBy: { createdAt: 'desc' },
      include: {
        chargeType: { select: { nameEn: true } },
        units: { include: { unit: { select: { name: true, propertyId: true, property: { select: { name: true, code: true } } } } } },
        subMeters: { select: { id: true, serialNo: true } },
        parent: { select: { id: true, serialNo: true } },
      },
    });
    return rows.map((m) => ({
      id: m.id,
      serialNo: m.serialNo,
      isActive: m.isActive,
      chargeTypeId: m.chargeTypeId,
      /** The property whose rate prices it. Null only for a meter that spans two
       *  properties from before that was refused — it has no rate at all. */
      propertyId: propertyOf(m),
      utility: m.chargeType.nameEn,
      units: m.units.map((mu) => ({
        unitId: mu.unitId,
        unitName: mu.unit.name,
        propertyName: propertyLabel(mu.unit.property),
        share: mu.share.toString(),
      })),
      /** The meters subtracted from this one before it is billed. */
      subMeters: m.subMeters.map((sm) => ({ id: sm.id, serialNo: sm.serialNo })),
      /** Set when this meter is itself deducted from a master. */
      parent: m.parent ? { id: m.parent.id, serialNo: m.parent.serialNo } : null,
    }));
  }),

  createMeter: withPermission('meter-reading.create')
    .input(
      z.object({
        chargeTypeId: z.string(),
        serialNo: z.string().optional(),
        unitIds: z.array(z.string()).min(1),
        /** Each unit's share of the meter, by unit id; a unit left out has 1. */
        shares: sharesInput,
        /** Meters whose usage is subtracted from this one before it is billed. */
        subMeterIds: z.array(z.string()).default([]),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      assertDistinctUnits(input.unitIds);
      const shares = checkedShares(input.unitIds, input.shares);
      await assertUtilityChargeType(ctx, input.chargeTypeId);
      await assertUnitsInOrg(ctx, input.unitIds);
      const propertyId = await assertOneProperty(ctx, input.unitIds);
      await assertDeductible(ctx, null, input.chargeTypeId, propertyId, input.subMeterIds);
      const m = await ctx.prisma.meter.create({
        data: {
          chargeTypeId: input.chargeTypeId,
          serialNo: input.serialNo || null,
          units: { create: input.unitIds.map((unitId) => ({ unitId, share: shares.get(unitId) ?? '1' })) },
        },
      });
      if (input.subMeterIds.length) {
        await ctx.prisma.meter.updateMany({ where: { id: { in: input.subMeterIds } }, data: { parentMeterId: m.id } });
      }
      return { id: m.id };
    }),

  updateMeter: withPermission('meter-reading.update')
    .input(
      z.object({
        id: z.string(),
        serialNo: z.string().optional().nullable(),
        isActive: z.boolean().optional(),
        unitIds: z.array(z.string()).min(1).optional(),
        /** Each unit's share, by unit id — of the units sent, or of the meter's
         *  own when none are. A unit left out keeps its share (1 when new). */
        shares: sharesInput,
        subMeterIds: z.array(z.string()).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const meter = await ctx.prisma.meter.findFirst({
        where: { id: input.id, units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined } } } } },
        select: {
          id: true,
          chargeTypeId: true,
          units: { select: { unitId: true, share: true, unit: { select: { propertyId: true } } } },
          parent: { select: UNIT_PROPERTIES },
          subMeters: { select: UNIT_PROPERTIES },
        },
      });
      if (!meter) throw new TRPCError({ code: 'NOT_FOUND' });
      // Units sent back unchanged are not a change. Only a change is held to the
      // one-property rule, so a meter from before it can still be renamed or
      // switched off without first being rearranged.
      const unitIds = input.unitIds;
      const unitsChanged =
        unitIds !== undefined &&
        !(unitIds.length === meter.units.length && unitIds.every((id) => meter.units.some((mu) => mu.unitId === id)));
      // The property the meter will be in once this is saved.
      let propertyId = propertyOf(meter);
      if (unitIds) {
        assertDistinctUnits(unitIds);
        await assertUnitsInOrg(ctx, unitIds);
      }
      if (unitIds && unitsChanged) {
        propertyId = await assertOneProperty(ctx, unitIds);
        // Moving a meter must not leave it in another property from its master,
        // or from the sub-meters it keeps. Sub-meters being replaced are checked
        // with the new set below.
        const kept = [...(meter.parent ? [meter.parent] : []), ...(input.subMeterIds ? [] : meter.subMeters)];
        if (kept.some((other) => propertyOf(other) !== propertyId)) {
          throw new TRPCError({ code: 'BAD_REQUEST', message: 'A sub-meter must be in the same property as its master' });
        }
      }
      if (input.subMeterIds) await assertDeductible(ctx, meter.id, meter.chargeTypeId, propertyId, input.subMeterIds, unitsChanged);
      // The shares the meter will have once this is saved, checked as a set. A
      // change reaches only what is still unbilled: a reading already on a note
      // for some units keeps what those notes charged.
      const finalUnits = unitIds ?? meter.units.map((mu) => mu.unitId);
      const shares = checkedShares(finalUnits, {
        ...Object.fromEntries(meter.units.map((mu) => [mu.unitId, mu.share.toString()])),
        ...(input.shares ?? {}),
      });
      await ctx.prisma.$transaction(async (tx) => {
        await tx.meter.update({
          where: { id: input.id },
          data: {
            ...(input.serialNo !== undefined ? { serialNo: input.serialNo || null } : {}),
            ...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
          },
        });
        if (input.unitIds || input.shares) {
          await tx.meterUnit.deleteMany({ where: { meterId: input.id, unitId: { notIn: finalUnits } } });
          for (const unitId of finalUnits) {
            const share = shares.get(unitId) ?? '1';
            await tx.meterUnit.upsert({
              where: { meterId_unitId: { meterId: input.id, unitId } },
              update: { share },
              create: { meterId: input.id, unitId, share },
            });
          }
        }
        if (input.subMeterIds) {
          // Detach any that are no longer nominated, then attach the current set.
          await tx.meter.updateMany({ where: { parentMeterId: input.id, id: { notIn: input.subMeterIds } }, data: { parentMeterId: null } });
          if (input.subMeterIds.length) {
            await tx.meter.updateMany({ where: { id: { in: input.subMeterIds } }, data: { parentMeterId: input.id } });
          }
        }
      });
      // Its units decide its rate, so readings that were waiting for one may
      // have one now — looked for once the new units have committed.
      if (unitsChanged) await ctx.metering.priceUnpriced({ id: input.id });
      return { id: input.id };
    }),

  /** Delete a meter. Blocked once it has readings (deactivate it instead). */
  deleteMeter: withPermission('meter-reading.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const meter = await ctx.prisma.meter.findFirst({
        where: { id: input.id, units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined } } } } },
        select: { _count: { select: { readings: true } } },
      });
      if (!meter) throw new TRPCError({ code: 'NOT_FOUND' });
      if (meter._count.readings > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This meter has ${meter._count.readings} reading(s) and can't be deleted; deactivate it instead.` });
      }
      await ctx.prisma.meter.delete({ where: { id: input.id } }); // meter_units cascade
      return { id: input.id };
    }),

  readings: withPermission('meter-reading.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.meterReading.findMany({
      where: { meter: { units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined, deletedAt: null } } } } } },
      orderBy: { periodEnd: 'desc' },
      take: 100,
      include: {
        meter: { select: { serialNo: true, chargeType: { select: { nameEn: true } }, units: { include: { unit: { select: { name: true } } } } } },
        claims: { select: { unitId: true, invoiceId: true } },
      },
    });
    // How many dial photos each reading carries, so the list can show which
    // ones still have no evidence behind them.
    const counts = await ctx.prisma.attachment.groupBy({
      by: ['ownerId'],
      where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'METER_READING', ownerId: { in: rows.map((r) => r.id) } },
      _count: { _all: true },
    });
    const evidenceCount = new Map(counts.map((c) => [c.ownerId, c._count._all]));
    // Why each unbilled reading has not reached a note. Billing skips silently,
    // which is right there and useless here — without this the list shows a
    // reading that has been sitting for months and gives no way to find out why.
    const blocked = await ctx.metering.explainUnbilled(ctx.organizationId ?? '', rows, hkToday());
    // Which notes each reading went out on, so the list can say so rather than
    // just "billed" — one meter's units can be on several.
    const billedIds = [...new Set(rows.flatMap((r) => r.claims.map((c) => c.invoiceId)))];
    const billedNumbers = new Map(
      (billedIds.length
        ? await ctx.prisma.invoice.findMany({ where: { id: { in: billedIds } }, select: { id: true, number: true } })
        : []
      ).map((i) => [i.id, i.number]),
    );
    return rows.map((r) => ({
      id: r.id,
      meterId: r.meterId,
      utility: r.meter.chargeType.nameEn,
      units: r.meter.units.map((mu) => mu.unit.name),
      readingStart: r.readingStart.toString(),
      readingEnd: r.readingEnd.toString(),
      periodStart: r.periodStart,
      periodEnd: r.periodEnd,
      grossAmount: r.grossAmount ? r.grossAmount.toFixed(2) : '0.00',
      evidence: evidenceCount.get(r.id) ?? 0,
      ...billingOf(r, billedNumbers),
      status: r.status,
      /** Set when a tenant declared this reading rather than the office. */
      submittedByTenant: r.submittedByUserId !== null,
      rejectionReason: r.rejectionReason,
      /** Null once it is billed in full, or while nothing holds back the units
       *  still unbilled. */
      blockedBy: blocked.get(r.id)?.code ?? null,
      /** For a master held by WAITING_SUB_METER: which sub-meters, and the day
       *  each needs a reading ending on or after. */
      waitingFor: blocked.get(r.id)?.waitingFor ?? null,
      readBy: blocked.get(r.id)?.readBy?.toISOString().slice(0, 10) ?? null,
    }));
  }),

  /** The meter's most recent reading, to open the next one from: a meter runs
   * continuously, so this period's start is last period's end — same figure,
   * same date, same dial photo. Null when the meter has never been read. */
  /** Accept a tenant's declaration. It is priced now, from the tariff in force
   *  at the moment it is accepted (or, if its property has no rate yet, when one
   *  is set), and only then can it reach a debit note. Numbers can be corrected
   *  first — the photo is what is being checked. */
  confirmReading: withPermission('meter-reading.update')
    .input(
      z.object({
        id: z.string(),
        readingStart: z.string().regex(/^\d+(\.\d{1,3})?$/).optional(),
        readingEnd: z.string().regex(/^\d+(\.\d{1,3})?$/).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const r = await ctx.prisma.meterReading.findFirst({
        where: { id: input.id, meter: { units: { some: { unit: { property: { organizationId: org } } } } } },
        select: { id: true, status: true, meterId: true, readingStart: true, readingEnd: true, periodStart: true, periodEnd: true, note: true },
      });
      if (!r) throw new TRPCError({ code: 'NOT_FOUND', message: 'Reading not found' });
      if (r.status !== 'PENDING') throw new TRPCError({ code: 'BAD_REQUEST', message: 'Only a reading awaiting review can be confirmed' });
      // Reuse the service so a confirmed declaration is priced by exactly the
      // same arithmetic as a reading the office typed itself.
      await ctx.metering.updateReading({
        organizationId: ctx.organizationId ?? '',
        id: r.id,
        readingStart: input.readingStart ?? r.readingStart.toString(),
        readingEnd: input.readingEnd ?? r.readingEnd.toString(),
        periodStart: r.periodStart.toISOString().slice(0, 10),
        periodEnd: r.periodEnd.toISOString().slice(0, 10),
        note: r.note,
      });
      await ctx.prisma.meterReading.update({
        where: { id: r.id },
        data: { status: 'CONFIRMED', reviewedByUserId: ctx.user.id, rejectionReason: null },
      });
      // Priced above while still awaiting review, which a rate set in between
      // skips; look again now that it is confirmed.
      await ctx.metering.priceUnpriced({ id: r.meterId });
      return { ok: true };
    }),

  /** Send a declaration back with a reason the tenant will see. */
  rejectReading: withPermission('meter-reading.update')
    .input(z.object({ id: z.string(), reason: z.string().min(1) }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const r = await ctx.prisma.meterReading.findFirst({
        where: { id: input.id, meter: { units: { some: { unit: { property: { organizationId: org } } } } } },
        select: { id: true, status: true },
      });
      if (!r) throw new TRPCError({ code: 'NOT_FOUND', message: 'Reading not found' });
      if (r.status !== 'PENDING') throw new TRPCError({ code: 'BAD_REQUEST', message: 'Only a reading awaiting review can be rejected' });
      await ctx.prisma.meterReading.update({
        where: { id: input.id },
        data: { status: 'REJECTED', reviewedByUserId: ctx.user.id, rejectionReason: input.reason },
      });
      return { ok: true };
    }),

  lastReading: withPermission('meter-reading.read')
    .input(z.object({ meterId: z.string() }))
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const last = await ctx.prisma.meterReading.findFirst({
        // Only a confirmed reading is a starting point — a declaration still
        // waiting to be checked is not yet a fact about the dial, and a rejected
        // one is a number someone has already decided is wrong. The tenant's own
        // form (portal.router myMeters) has always said so; the staff form
        // opening from a figure the portal refuses to open from is the same meter
        // answering two different questions.
        where: { meterId: input.meterId, status: 'CONFIRMED', meter: { units: { some: { unit: { property: { organizationId: org, deletedAt: null } } } } } },
        orderBy: [{ periodEnd: 'desc' }, { createdAt: 'desc' }],
        select: { id: true, readingEnd: true, periodEnd: true },
      });
      if (!last) return null;
      const endPhoto = await ctx.prisma.attachment.findFirst({
        where: { organizationId: org, ownerType: 'METER_READING', ownerId: last.id, role: 'END' },
        select: { id: true, filename: true, mimeType: true },
      });
      return {
        readingEnd: last.readingEnd.toString(),
        periodEnd: last.periodEnd,
        endPhoto,
      };
    }),

  /** The dial photos captured for one reading — printed on the debit note that
   * bills it, so the list is keyed by role rather than upload order. */
  readingEvidence: withPermission('meter-reading.read')
    .input(z.object({ readingId: z.string() }))
    .query(({ ctx, input }) =>
      ctx.prisma.attachment.findMany({
        where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'METER_READING', ownerId: input.readingId },
        orderBy: { createdAt: 'asc' },
        select: { id: true, filename: true, mimeType: true, role: true },
      }),
    ),

  createReading: withPermission('meter-reading.create')
    .input(
      z.object({
        meterId: z.string(),
        readingStart: z.string(),
        readingEnd: z.string(),
        periodStart: z.string(),
        periodEnd: z.string(),
        note: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.metering.createReading({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  updateReading: withPermission('meter-reading.update')
    .input(
      z.object({
        id: z.string(),
        readingStart: z.string(),
        readingEnd: z.string(),
        periodStart: z.string(),
        periodEnd: z.string(),
        note: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.metering.updateReading({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  /** Delete a reading. Ledger-safe: issued invoices froze their amounts, so this
   * only affects the reading record and future drafts. */
  deleteReading: withPermission('meter-reading.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // A billed reading backs a charge on a live debit note; deleting it would
      // strip the evidence out from under that charge.
      const reading = await ctx.prisma.meterReading.findFirst({
        where: { id: input.id, meter: { units: { some: { unit: { property: { organizationId: ctx.organizationId ?? undefined } } } } } },
        select: { _count: { select: { claims: true } } },
      });
      if (!reading) throw new TRPCError({ code: 'NOT_FOUND' });
      if (reading._count.claims > 0) {
        throw new TRPCError({
          code: 'CONFLICT',
          message:
            '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.',
        });
      }
      await ctx.prisma.meterReading.delete({ where: { id: input.id } });
      return { id: input.id };
    }),

});
