/**
 * Functional smoke for master meters and the sub-meters deducted from them.
 * Standalone, self-cleaning.
 *
 * The real case: one electricity bill arrives for a master meter; the flats that
 * have their own sub-meters are subtracted, and only what remains is billed to
 * the units behind the master. Two things make this easy to get wrong and are
 * asserted here — the deduction is in USAGE and re-priced once (subtracting
 * money would drop the tariff's fixed charge once per sub-meter), and a master
 * whose sub-meters have not been read up to about its date is left unbilled
 * rather than billed in full.
 *
 * The master is the power company's meter, read on its billing dates; the
 * sub-meters are read on whatever day staff or tenants photograph them. So a
 * sub-meter reading counts for the bill whose date it falls within the
 * organisation's tolerance of, and one read late simply comes off the next
 * bill — C, F and G hold that, and that nothing is deducted twice or lost.
 *
 * Runs in its own organisation, so the real one's tolerance setting decides
 * nothing here.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/meter-deduction-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 { SUB_METER_TOLERANCE_KEY } from '../src/metering/sub-meter-deduction';
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);
const ORG_CODE = 'ZZ-DED-ORG';

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

const created: { invoiceIds: string[]; leaseId?: string; propertyId?: string; unitIds: string[]; tenantId?: string; meterIds: string[]; ctId?: string } = { invoiceIds: [], unitIds: [], meterIds: [] };

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

async function main() {
  await purgeStale();

  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Deduction smoke org' } })).id;
  const rentCt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING' } });
  const setTolerance = (days: number) =>
    prisma.setting.upsert({
      where: { organizationId_key: { organizationId: orgId, key: SUB_METER_TOLERANCE_KEY } },
      update: { value: days },
      create: { organizationId: orgId, key: SUB_METER_TOLERANCE_KEY, value: days },
    });
  await setTolerance(7);

  // Rate 10 per unit PLUS a fixed 30 — with a fixed charge of 0 a money-based
  // deduction would give the same answer and the bug would be invisible.
  const util = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZPWR', nameEn: 'ZZ Power', category: 'UTILITY', isActive: true, sortOrder: 999 } });
  created.ctId = util.id;

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Ded Tenant' } });
  created.tenantId = tenant.id;
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: 'ZZ Ded Property', units: { create: [{ name: 'ZZ Flat A' }, { name: 'ZZ Flat B' }, { name: 'ZZ Shop' }, { name: 'ZZ Store' }] } },
    include: { units: true },
  });
  created.propertyId = property.id;
  await prisma.utilityTariff.create({ data: { chargeTypeId: util.id, propertyId: property.id, unitRate: '10', fixedCharge: '30' } });
  const [flatA, flatB, shop, store] = property.units;
  created.unitIds = property.units.map((u) => u.id);

  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-DED-${property.id.slice(-5)}`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: shop.id }, { unitId: store.id }] },
      chargeRules: { create: [
        { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
        // Amount 0 is the marker that says this lease is billed for ZZ Power.
        { chargeTypeId: util.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 },
      ] },
    },
  });
  created.leaseId = lease.id;

  const mkMeter = async (serialNo: string, unitIds: string[], parentMeterId?: string) => {
    const m = await prisma.meter.create({
      data: { chargeTypeId: util.id, serialNo, parentMeterId: parentMeterId ?? null, units: { create: unitIds.map((unitId) => ({ unitId })) } },
    });
    created.meterIds.push(m.id);
    return m;
  };
  const reading = (meterId: string, from: string, to: string, start: string, end: string, gross: string) =>
    prisma.meterReading.create({ data: { meterId, readingStart: start, readingEnd: end, periodStart: new Date(from), periodEnd: new Date(to), grossAmount: gross } });

  console.log('Fixture: master covering the Shop, less Flat A and Flat B sub-meters\n');

  console.log('A. One bill, two sub-meters deducted');
  const master = await mkMeter('ZZ-PWR-000', [shop.id]);
  const subA = await mkMeter('ZZ-PWR-00A', [flatA.id], master.id);
  const subB = await mkMeter('ZZ-PWR-00B', [flatB.id], master.id);
  // Master 1000 units; A used 300, B used 200 → 500 left for the Shop.
  await reading(master.id, '2019-12-01', '2019-12-31', '0', '1000', '10030');
  await reading(subA.id, '2019-12-01', '2019-12-31', '0', '300', '3030');
  await reading(subB.id, '2019-12-01', '2019-12-31', '0', '200', '2030');

  const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  created.invoiceIds.push(inv.id);
  const lines = await linesOf(inv.id);
  const power = lines.filter((l) => l.description.includes('ZZ Power'));
  ck('A1 one line for the master, on the unit it covers', power.length === 1 && power[0].description.includes('ZZ Shop'), `got ${power.map((l) => l.description)}`);
  // 500 × 10 + 30 = 5030. Deducting money instead would give
  // 10030 − 3030 − 2030 = 4970, i.e. the fixed charge subtracted three times.
  ck('A2 the remainder is re-priced from the tariff (500 × 10 + 30)', power[0]?.amount.toString() === '5030', `got ${power[0]?.amount}`);
  const meta = (power[0]?.meta ?? {}) as Record<string, unknown>;
  ck('A3 the line records the net usage', String(meta.usage) === '500', `got ${meta.usage}`);
  ck('A4 and how it was arrived at', typeof meta.deductionNote === 'string' && String(meta.deductionNote).includes('ZZ-PWR-00A'), `got ${meta.deductionNote}`);
  ck('A5 no share percentage survives on the line', !('sharePercent' in meta));
  const masterReading = await prisma.meterReading.findFirstOrThrow({ where: { meterId: master.id }, select: { claims: { select: { invoiceId: true } } } });
  ck('A6 the master reading is claimed by this note', masterReading.claims.length > 0 && masterReading.claims.every((c) => c.invoiceId === inv.id));
  const subClaims = await prisma.meterReading.count({ where: { meterId: { in: [subA.id, subB.id] }, claims: { some: {} } } });
  ck('A7 the sub readings stay unclaimed — they bill on their own units', subClaims === 0, `got ${subClaims}`);

  console.log('\nB. A missing sub-meter reading holds the master back');
  await reading(master.id, '2020-01-01', '2020-01-31', '1000', '1800', '8030');
  await reading(subA.id, '2020-01-01', '2020-01-31', '300', '500', '2030');
  // Flat B was not read this month.
  const inv2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02' });
  created.invoiceIds.push(inv2.id);
  ck('B1 the master is not billed while a deduction is unknown', !(await linesOf(inv2.id)).some((l) => l.description.includes('ZZ Power')));
  const held = await prisma.meterReading.findFirstOrThrow({ where: { meterId: master.id, periodStart: new Date('2020-01-01') }, select: { _count: { select: { claims: true } } } });
  ck('B2 it stays in the queue rather than being consumed', held._count.claims === 0);

  await reading(subB.id, '2020-01-01', '2020-01-31', '200', '400', '2030');
  const inv3 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03' });
  created.invoiceIds.push(inv3.id);
  const late = (await linesOf(inv3.id)).filter((l) => l.description.includes('ZZ Power'));
  // 800 − 200 − 200 = 400 → 400 × 10 + 30
  ck('B3 once the last reading is in, a later note picks it up', late.length === 1 && late[0].amount.toString() === '4030', `got ${late.map((l) => l.amount)}`);

  console.log('\nC. Sub-meters read on their own days, a few days either side of the bill');
  // The master is the power company's, read on its date and typed the way its
  // bill prints it — 1 Feb to 29 Feb, after January's 1 Jan to 31 Jan. Flat A
  // was photographed two days before the date, Flat B three days after.
  await reading(master.id, '2020-02-01', '2020-02-29', '1800', '2000', '2030');
  await reading(subA.id, '2020-01-31', '2020-02-27', '500', '560', '630');
  await reading(subB.id, '2020-01-31', '2020-03-03', '400', '450', '530');
  const inv4 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-04' });
  created.invoiceIds.push(inv4.id);
  const feb = (await linesOf(inv4.id)).filter((l) => l.description.includes('ZZ Power'));
  // 200 − 60 − 50 = 90 → 90 × 10 + 30
  ck('C1 both come off the bill they sit either side of', feb.length === 1 && feb[0].amount.toString() === '930', `got ${feb.map((l) => l.amount)}`);

  console.log('\nD. A plain meter over several units splits evenly');
  const plain = await mkMeter('ZZ-PWR-100', [shop.id, store.id]);
  await reading(plain.id, '2020-03-01', '2020-03-31', '0', '100', '1030');
  const inv5 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-05' });
  created.invoiceIds.push(inv5.id);
  const evenly = (await linesOf(inv5.id)).filter((l) => l.description.includes('ZZ-PWR-100') || l.description.includes('ZZ Power'));
  const plainLines = evenly.filter((l) => ((l.meta ?? {}) as Record<string, unknown>).meterId === plain.id);
  ck('D1 one line per covered unit', plainLines.length === 2, `got ${plainLines.length}`);
  ck('D2 the two halves sum to the gross', plainLines.reduce((s, l) => s + Number(l.amount), 0) === 1030, `got ${plainLines.map((l) => l.amount)}`);

  console.log('\nE. Billing one unit of a two-unit meter bills half, not all');
  await reading(plain.id, '2020-04-01', '2020-04-30', '100', '200', '1030');
  const invSplit = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-06', unitIds: [shop.id] });
  created.invoiceIds.push(invSplit.id);
  const half = (await linesOf(invSplit.id)).filter((l) => ((l.meta ?? {}) as Record<string, unknown>).meterId === plain.id);
  ck('E1 only the billed unit gets a line', half.length === 1, `got ${half.length}`);
  ck('E2 for its half, not the whole meter', half[0]?.amount.toString() === '515', `got ${half[0]?.amount}`);

  const lineFor = (lines: Awaited<ReturnType<typeof linesOf>>, readingId: string) =>
    lines.find((l) => ((l.meta ?? {}) as Record<string, unknown>).meterReadingId === readingId);
  const takenFrom = (line: Awaited<ReturnType<typeof linesOf>>[number] | undefined, serial: string) =>
    Number(new RegExp(`- ([\\d.]+) \\(${serial}\\)`).exec(String(((line?.meta ?? {}) as Record<string, unknown>).deductionNote))?.[1] ?? NaN);

  console.log('\nF. A sub-meter read long after a bill comes off the next one — once, and in full');
  const mar = await reading(master.id, '2020-03-01', '2020-03-31', '2000', '2300', '3030');
  await reading(subA.id, '2020-02-27', '2020-03-29', '560', '600', '430');
  // Flat B's next photo is not until 25 April, so none of it falls near March's date.
  await reading(subB.id, '2020-03-03', '2020-04-25', '450', '520', '730');
  const apr = await reading(master.id, '2020-04-01', '2020-04-30', '2300', '2500', '2030');
  await reading(subA.id, '2020-03-29', '2020-04-28', '600', '640', '430');
  const inv6 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-07' });
  created.invoiceIds.push(inv6.id);
  const lines6 = await linesOf(inv6.id);
  // March: 300 − 40 − 0 = 260 → 2630. April: 200 − 40 − 70 = 90 → 930.
  ck('F1 March takes Flat A off, and nothing of Flat B yet', lineFor(lines6, mar.id)?.amount.toString() === '2630', `got ${lineFor(lines6, mar.id)?.amount}`);
  ck('F2 April takes Flat B’s late reading off whole', lineFor(lines6, apr.id)?.amount.toString() === '930', `got ${lineFor(lines6, apr.id)?.amount}`);
  const febLine = (await linesOf(inv4.id)).find((l) => l.description.includes('ZZ Power'));
  const flatBTaken = takenFrom(febLine, 'ZZ-PWR-00B') + takenFrom(lineFor(lines6, mar.id), 'ZZ-PWR-00B') + takenFrom(lineFor(lines6, apr.id), 'ZZ-PWR-00B');
  ck('F3 across the three bills Flat B is deducted exactly what its dial moved (400 → 520)', flatBTaken === 120, `got ${flatBTaken}`);

  console.log('\nG. Not read up to about the date: the master waits — how near is the organisation’s call');
  const may = await reading(master.id, '2020-05-01', '2020-05-31', '2500', '2700', '2030');
  // Flat A last photographed on 20 May, eleven days before the bill.
  await reading(subA.id, '2020-04-28', '2020-05-20', '640', '660', '230');
  await reading(subB.id, '2020-04-25', '2020-05-29', '520', '560', '430');
  const holdOf = async (readingId: string) => {
    const r = await prisma.meterReading.findUniqueOrThrow({ where: { id: readingId }, include: { claims: { select: { unitId: true } } } });
    return (await metering.explainUnbilled(orgId, [r], new Date('2020-12-15'))).get(r.id) ?? null;
  };
  const blockOf = async (readingId: string) => (await holdOf(readingId))?.code ?? null;
  const inv7 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-08' });
  created.invoiceIds.push(inv7.id);
  ck('G1 at 7 days, eleven days short holds the master back', !lineFor(await linesOf(inv7.id), may.id));
  const hold = await holdOf(may.id);
  ck('G2 and the readings list says why', hold?.code === 'WAITING_SUB_METER', `got ${hold?.code}`);
  // Flat B was read on 29 May, near enough; only Flat A is holding it.
  ck('G2a naming the one sub-meter it waits on, and its flat', JSON.stringify(hold?.waitingFor) === JSON.stringify([{ serialNo: 'ZZ-PWR-00A', units: ['ZZ Flat A'] }]), `got ${JSON.stringify(hold?.waitingFor)}`);
  ck('G2b and how far it needs reading: 31 May less 7 days', hold?.readBy?.toISOString().slice(0, 10) === '2020-05-24', `got ${hold?.readBy?.toISOString()}`);
  await setTolerance(14);
  ck('G3 at 14 days the same readings are near enough', (await blockOf(may.id)) === null, `got ${await blockOf(may.id)}`);
  const inv8 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-09' });
  created.invoiceIds.push(inv8.id);
  // 200 − 20 − 40 = 140 → 1430
  ck('G4 and billing agrees with the list', lineFor(await linesOf(inv8.id), may.id)?.amount.toString() === '1430', `got ${lineFor(await linesOf(inv8.id), may.id)?.amount}`);
}

async function purgeStale() {
  const meters = await prisma.meter.findMany({ where: { serialNo: { startsWith: 'ZZ-PWR-' } }, 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: 'ZZ-DED' } }, select: { id: true } });
  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 Ded 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: 'ZZ Ded Tenant' } });
  const ct = await prisma.chargeType.findFirst({ where: { code: 'ZZPWR' }, select: { id: true } });
  if (ct) {
    await prisma.utilityTariff.deleteMany({ where: { chargeTypeId: ct.id } });
    await prisma.chargeType.delete({ where: { id: ct.id } }).catch(() => {});
  }
  // The organisation last: everything above hangs off it.
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (org) {
    await prisma.setting.deleteMany({ where: { organizationId: org.id } });
    await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
    await prisma.organization.delete({ where: { id: org.id } });
  }
}

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); });
