/**
 * Functional smoke for two things that were previously silent.
 *
 * 1. A meter does not stop when the unit changes hands. Utilities bill in
 *    arrears with no lower bound, so a reading that was never billed keeps
 *    waiting and lands on whatever note is raised next — which, after a
 *    handover, is the new tenant's. It must not: the usage is the previous
 *    tenant's. A renewal by the SAME tenant is the case that must still bill,
 *    or the boundary reading would be lost to everyone.
 *
 * 2. Every reason billing skips a reading is reported, so a reading sitting
 *    unbilled for months can be explained instead of guessed at.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/reading-handover-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { BillingService } from '../src/billing/billing.service';
import { ApprovalService } from '../src/approvals/approval.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { MeteringService } from '../src/metering/metering.service';
import { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
const metering = new MeteringService(prisma);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

const REF = 'ZZ-HND';
const SERIAL = 'ZZ-HND-';

const linesOf = (invoiceId: string) =>
  prisma.invoiceLine.findMany({ where: { invoiceId }, orderBy: { sortOrder: 'asc' }, select: { description: true, amount: true, meta: true } });

/** The reasons, for the readings given, as the metering page would show them. */
async function blocks(orgId: string, asOf: Date) {
  const rows = await prisma.meterReading.findMany({
    where: { meter: { serialNo: { startsWith: SERIAL } } },
    select: { id: true, meterId: true, periodStart: true, periodEnd: true, readingStart: true, readingEnd: true, grossAmount: true, status: true, claims: { select: { unitId: true } } },
  });
  const held = await metering.explainUnbilled(orgId, rows, asOf);
  return new Map([...held].map(([id, h]) => [id, h.code]));
}

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('no org');
  const orgId = org.id;
  const rentCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'RECURRING', glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!rentCt) throw new Error('no rent charge type');

  await purgeStale();

  const water = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZHWT', nameEn: 'ZZ Handover Water', category: 'UTILITY', isActive: true, sortOrder: 998 } });
  // A second utility the leases are NOT contracted for, and one with no rate at all.
  const gas = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZHGS', nameEn: 'ZZ Handover Gas', category: 'UTILITY', isActive: true, sortOrder: 998 } });
  const untariffed = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZHNR', nameEn: 'ZZ Handover Norate', category: 'UTILITY', isActive: true, sortOrder: 998 } });

  const oldTenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Hand Old' } });
  const newTenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Hand New' } });
  const stayer = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Hand Stayer' } });

  const property = await prisma.property.create({
    data: { organizationId: orgId, name: 'ZZ Hand Property', units: { create: [{ name: 'ZZ Hand Flat' }, { name: 'ZZ Hand Shop' }, { name: 'ZZ Hand Store' }] } },
    include: { units: true },
  });
  await prisma.utilityTariff.create({ data: { chargeTypeId: water.id, propertyId: property.id, unitRate: '10', fixedCharge: '0' } });
  await prisma.utilityTariff.create({ data: { chargeTypeId: gas.id, propertyId: property.id, unitRate: '5', fixedCharge: '0' } });
  const [flat, shop, store] = property.units;

  const rules = (extra: { chargeTypeId: string }[] = []) => ({
    create: [
      { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false, sortOrder: 0 },
      { chargeTypeId: water.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false, sortOrder: 1 },
      ...extra.map((e, i) => ({ ...e, amount: '0', frequencyMonths: 1, timing: 'ARREARS' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false, sortOrder: 2 + i })),
    ],
  });

  const mkLease = (ref: string, tenantId: string, unitId: string, start: string, end: string, status: 'ACTIVE' | 'ENDED', renewedFromId?: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `${REF}-${ref}`, tenantId, status, currency: 'HKD',
        startDate: new Date(start), endDate: new Date(end), depositMonths: 0, renewedFromId: renewedFromId ?? null,
        units: { create: [{ unitId }] }, chargeRules: rules(),
      },
    });

  const mkMeter = async (serial: string, chargeTypeId: string, unitIds: string[], parentMeterId?: string) =>
    prisma.meter.create({ data: { chargeTypeId, serialNo: SERIAL + serial, parentMeterId: parentMeterId ?? null, units: { create: unitIds.map((unitId) => ({ unitId })) } } });

  const reading = (meterId: string, from: string, to: string, start: string, end: string, gross: string | null, status: 'CONFIRMED' | 'PENDING' = 'CONFIRMED') =>
    prisma.meterReading.create({ data: { meterId, readingStart: start, readingEnd: end, periodStart: new Date(from), periodEnd: new Date(to), grossAmount: gross, status } });

  console.log('A. The unit changes hands — the old tenant\'s water is not the new tenant\'s');
  // Old tenant to end-2019, new tenant from 2020. The meter was last read in
  // November 2019 and that reading was never billed.
  await mkLease('OLD', oldTenant.id, flat.id, '2019-01-01', '2019-12-31', 'ENDED');
  const newLease = await mkLease('NEW', newTenant.id, flat.id, '2020-01-01', '2100-01-01', 'ACTIVE');
  const flatMeter = await mkMeter('FLAT', water.id, [flat.id]);
  const strayId = (await reading(flatMeter.id, '2019-11-01', '2019-11-30', '0', '100', '1000')).id;
  // And one squarely inside the new tenancy, which must still bill.
  await reading(flatMeter.id, '2020-01-01', '2020-01-31', '100', '160', '600');

  const blocksBefore = await blocks(orgId, new Date('2020-03-15'));
  ck('A1 the stray reading is reported as the previous tenant\'s', blocksBefore.get(strayId) === 'PREVIOUS_TENANT', `got ${blocksBefore.get(strayId)}`);

  const invNew = await billing.generateDraft({ organizationId: orgId, leaseId: newLease.id, period: '2020-03' });
  const newLines = await linesOf(invNew.id);
  const waterLines = newLines.filter((l) => l.description.includes('ZZ Handover Water'));
  ck('A2 only the reading inside the new tenancy is billed', waterLines.length === 1 && waterLines[0].amount.toString() === '600', `got ${waterLines.map((l) => `${l.description}=${l.amount}`)}`);
  const stray = await prisma.meterReading.findUniqueOrThrow({ where: { id: strayId }, select: { _count: { select: { claims: true } } } });
  ck('A3 and the old tenant\'s reading is left unclaimed, not consumed', stray._count.claims === 0);

  console.log('\nB. A renewal by the same tenant still bills across the boundary');
  const first = await mkLease('RN1', stayer.id, shop.id, '2019-01-01', '2019-12-31', 'ENDED');
  const renewal = await mkLease('RN2', stayer.id, shop.id, '2020-01-01', '2100-01-01', 'ACTIVE', first.id);
  const shopMeter = await mkMeter('SHOP', water.id, [shop.id]);
  const boundaryId = (await reading(shopMeter.id, '2019-11-01', '2019-11-30', '0', '70', '700')).id;

  const blocksB = await blocks(orgId, new Date('2020-03-15'));
  ck('B1 nothing is holding the boundary reading back', blocksB.get(boundaryId) === undefined, `got ${blocksB.get(boundaryId)}`);
  const invRenew = await billing.generateDraft({ organizationId: orgId, leaseId: renewal.id, period: '2020-03' });
  const renewWater = (await linesOf(invRenew.id)).filter((l) => l.description.includes('ZZ Handover Water'));
  ck('B2 the same tenant is billed for it after renewing', renewWater.length === 1 && renewWater[0].amount.toString() === '700', `got ${renewWater.map((l) => l.amount)}`);

  console.log('\nC. Every other reason a reading is skipped is named');
  // No charge rule: the store's lease is contracted for water, not gas.
  await mkLease('STO', newTenant.id, store.id, '2019-01-01', '2100-01-01', 'ACTIVE');
  const gasMeter = await mkMeter('GAS', gas.id, [store.id]);
  const noRuleId = (await reading(gasMeter.id, '2019-06-01', '2019-06-30', '0', '50', '250')).id;

  // No tariff at all on the utility, so the reading is stored unpriced.
  const norateMeter = await mkMeter('NORATE', untariffed.id, [store.id]);
  const noTariffId = (await reading(norateMeter.id, '2019-06-01', '2019-06-30', '0', '50', null)).id;

  // A master whose sub-meters read more than it did…
  const master = await mkMeter('MASTER', water.id, [store.id]);
  const sub = await mkMeter('SUB', water.id, [flat.id], master.id);
  const exceedsId = (await reading(master.id, '2019-07-01', '2019-07-31', '0', '100', '1000')).id;
  await reading(sub.id, '2019-07-01', '2019-07-31', '0', '500', '5000');
  // …and its next reading, with the sub-meter not read since. The latest on
  // purpose: a sub-meter reading after it would count as read up to its date.
  const waitingId = (await reading(master.id, '2019-08-01', '2019-08-31', '100', '1000', '9000')).id;

  // Awaiting review: a tenant's own declaration.
  const pendingId = (await reading(shopMeter.id, '2019-09-01', '2019-09-30', '70', '90', '200', 'PENDING')).id;

  // Not due yet: read inside the current month, so no note covers it in arrears.
  const today = new Date(new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' }) + 'T00:00:00.000Z');
  const monthStart = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
  const notDueId = (await reading(shopMeter.id, monthStart.toISOString().slice(0, 10), today.toISOString().slice(0, 10), '90', '95', '50')).id;

  const b = await blocks(orgId, today);
  ck('C1 no charge rule on the lease for that utility', b.get(noRuleId) === 'NO_CHARGE_RULE', `got ${b.get(noRuleId)}`);
  ck('C2 the utility has no rate set', b.get(noTariffId) === 'NO_TARIFF', `got ${b.get(noTariffId)}`);
  ck('C3 waiting on a sub-meter reading', b.get(waitingId) === 'WAITING_SUB_METER', `got ${b.get(waitingId)}`);
  ck('C4 sub-meters read more than the master', b.get(exceedsId) === 'SUB_EXCEEDS_MASTER', `got ${b.get(exceedsId)}`);
  ck('C5 a tenant declaration still awaiting review', b.get(pendingId) === 'AWAITING_REVIEW', `got ${b.get(pendingId)}`);
  ck('C6 read this month, so not due in arrears yet', b.get(notDueId) === 'NOT_DUE_YET', `got ${b.get(notDueId)}`);

  console.log('\nD. The reasons agree with what billing actually does');
  // Every reading the diagnostic calls unblocked, and only those, should reach a
  // note — the point of the feature is that the two never disagree.
  const invStore = await billing.generateDraft({ organizationId: orgId, leaseId: (await prisma.lease.findFirstOrThrow({ where: { reference: `${REF}-STO` }, select: { id: true } })).id, period: '2020-03' });
  const storeLines = await linesOf(invStore.id);
  const blockedIds = [noRuleId, noTariffId, waitingId, exceedsId, pendingId, notDueId];
  const billedNow = new Set(storeLines.map((l) => ((l.meta ?? {}) as Record<string, unknown>).meterReadingId).filter(Boolean));
  ck('D1 not one blocked reading reached the note', blockedIds.every((id) => !billedNow.has(id)), `billed ${[...billedNow]}`);
  const stillWaiting = await prisma.meterReading.findMany({ where: { id: { in: blockedIds } }, select: { id: true, _count: { select: { claims: true } } } });
  ck('D2 they all stay in the queue for when they are fixed', stillWaiting.every((r) => r._count.claims === 0));
}

async function purgeStale() {
  const meters = await prisma.meter.findMany({ where: { serialNo: { startsWith: SERIAL } }, select: { id: true } });
  const ids = meters.map((m) => m.id);
  if (ids.length) {
    await prisma.meterReading.deleteMany({ where: { meterId: { in: ids } } });
    await prisma.meter.updateMany({ where: { id: { in: ids } }, data: { parentMeterId: null } });
    await prisma.meterUnit.deleteMany({ where: { meterId: { in: ids } } });
    await prisma.meter.deleteMany({ where: { id: { in: ids } } });
  }
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  // Renewals point at each other, so break the link before deleting either.
  await prisma.lease.updateMany({ where: { id: { in: leases.map((l) => l.id) } }, data: { renewedFromId: null } });
  for (const l of leases) {
    const invIds = (await prisma.invoice.findMany({ where: { leaseId: l.id }, select: { id: true } })).map((i) => i.id);
    if (invIds.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: invIds } }, { lines: { some: { invoiceId: { in: invIds } } } }] }, select: { id: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
      }
      await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
      await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    }
    await prisma.leaseUnit.deleteMany({ where: { leaseId: l.id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: l.id } });
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  const props = await prisma.property.findMany({ where: { name: 'ZZ Hand Property' }, select: { id: true, units: { select: { id: true } } } });
  for (const p of props) {
    await prisma.unit.deleteMany({ where: { id: { in: p.units.map((u) => u.id) } } });
    await prisma.property.delete({ where: { id: p.id } }).catch(() => {});
  }
  await prisma.tenant.deleteMany({ where: { name: { startsWith: 'ZZ Hand ' } } });
  const cts = await prisma.chargeType.findMany({ where: { code: { in: ['ZZHWT', 'ZZHGS', 'ZZHNR'] } }, select: { id: true } });
  if (cts.length) {
    await prisma.utilityTariff.deleteMany({ where: { chargeTypeId: { in: cts.map((c) => c.id) } } });
    await prisma.chargeType.deleteMany({ where: { id: { in: cts.map((c) => c.id) } } }).catch(() => {});
  }
}

async function cleanup() {
  try { await purgeStale(); console.log('\nCleanup: OK'); }
  catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
}

main().catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); }).finally(async () => { await cleanup(); await prisma.$disconnect(); console.log(`\n==== ${pass} passed, ${fail} failed ====`); process.exit(fail > 0 ? 1 : 0); });
