/**
 * Functional smoke: one meter, unequal shares, billed over several notes.
 *
 * The office's case: a tenant's electricity is the landlord's CLP meter less
 * the pantry's and units 611-613's sub-meters, and it is split six ways over
 * the tenant's eighteen units — the last sixth three ways again — and billed on
 * eight debit notes of one lease. Two things stood in the way: a meter's cost
 * was split evenly between its units, and a reading was claimed whole by the
 * first note that billed any of it, so every other note sharing the meter
 * silently billed nothing.
 *
 * What has to hold, and is asserted: each unit takes its share of the meter;
 * each note bills its own units' shares and claims only those; the parts add up
 * to the meter to the cent; a reading reads as partly billed until every unit
 * with a share is on a note; voiding, rebuilding and taking a line off release
 * exactly that note's shares; a unit with no share needs no note; and a lease
 * with billing groups is raised one note per group, every month, once.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/meter-share-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal, sum } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.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';
import { invoicesRouter } from '../src/trpc/routers/invoices.router';
import { leasesRouter } from '../src/trpc/routers/leases.router';
import { meteringRouter } from '../src/trpc/routers/metering.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

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}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const ORG_CODE = 'ZZ-MSH-ORG';
const XIAOMI = ['614', '615', '616', '617', '618', '619', '620', '621', '622', '623', '624', '625', '626', '627', '628', '629', '630', '631'];

function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-msh-staff', email: 'zz-msh@rms.local', name: 'ZZ MSH', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: ['meter-reading.read', 'meter-reading.create', 'meter-reading.update'],
  };
  return { prisma, user, organizationId: orgId, metering } as unknown as Context;
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Meter share org' } })).id;
  const api = meteringRouter.createCaller(staffCtx(orgId));
  const elec = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ELEC', nameEn: 'Electricity', category: 'UTILITY' } });
  const names = ['611', '612', '613', 'Pantry', ...XIAOMI, 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7'];
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: 'ZZ MSH Tower', units: { create: names.map((name) => ({ name })) } },
    include: { units: true },
  });
  const u = Object.fromEntries(property.units.map((x) => [x.name, x.id]));
  await prisma.utilityTariff.create({ data: { chargeTypeId: elec.id, propertyId: property.id, unitRate: '1', fixedCharge: '0' } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Xiaomi' } });
  const lease = (ref: string, unitNames: string[]) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-MSH-${ref}`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
        startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: unitNames.map((n) => ({ unitId: u[n] })) },
        chargeRules: { create: [{ chargeTypeId: elec.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
      },
    });
  const reading = (meterId: string, start: string, end: string) =>
    prisma.meterReading.create({
      data: { meterId, readingStart: start, readingEnd: end, periodStart: new Date('2020-01-01'), periodEnd: new Date('2020-01-31'), grossAmount: new Decimal(end).minus(start).toFixed(2), status: 'CONFIRMED' },
    });
  const note = (leaseId: string, unitNames?: string[]) =>
    billing.generateDraft({ organizationId: orgId, leaseId, period: '2020-02', ...(unitNames ? { unitIds: unitNames.map((n) => u[n]) } : {}) });
  const elecLines = (invoiceId: string) => prisma.invoiceLine.findMany({ where: { invoiceId, chargeTypeId: elec.id }, orderBy: { sortOrder: 'asc' } });
  const elecTotal = async (invoiceId: string) => sum((await elecLines(invoiceId)).map((l) => l.amount.toString())).toFixed(2);
  const listed = async (readingId: string) => (await api.readings()).find((r) => r.id === readingId)!;

  console.log('A. A meter gives each of its units a share');
  ck('A2 a share that is not a number is refused', (await refused(() => api.createMeter({ chargeTypeId: elec.id, unitIds: [u.S1], shares: { [u.S1]: '1/6' } }))).includes('A share must be a number'));
  // The pantry is billed to no one: it is read only to come off the CLP master.
  const pantry = await api.createMeter({ chargeTypeId: elec.id, serialNo: 'ZZ-MSH-PANTRY', unitIds: [u.Pantry], shares: { [u.Pantry]: '0' } });
  const m611 = await api.createMeter({ chargeTypeId: elec.id, serialNo: 'ZZ-MSH-611', unitIds: [u['611'], u['612'], u['613']] });
  // Six parts: 614, 615, 616, 617-622, 623-627 a sixth each; the last sixth three
  // ways, 628-629, 630 and 631. Shares out of 36; 623-627 split theirs as 1.2s.
  const shareOf: Record<string, string> = { '614': '6', '615': '6', '616': '6', '628': '1', '629': '1', '630': '2', '631': '2' };
  for (const n of ['617', '618', '619', '620', '621', '622']) shareOf[n] = '1';
  for (const n of ['623', '624', '625', '626', '627']) shareOf[n] = '1.2';
  const clp = await api.createMeter({
    chargeTypeId: elec.id, serialNo: 'ZZ-MSH-CLP', unitIds: XIAOMI.map((n) => u[n]),
    shares: Object.fromEntries(XIAOMI.map((n) => [u[n], shareOf[n]])), subMeterIds: [pantry.id, m611.id],
  });
  const clpListed = (await api.meters()).find((m) => m.id === clp.id)!;
  ck('A3 the shares are kept as given', clpListed.units.find((x) => x.unitName === '614')?.share === '6' && clpListed.units.find((x) => x.unitName === '623')?.share === '1.2',
    JSON.stringify(clpListed.units.slice(0, 3)));

  console.log('\nB. 小米: CLP less the pantry and 611-613, six ways, on eight notes of one lease');
  const xiaomi = await lease('XM', XIAOMI);
  const neighbour = await lease('NB', ['611', '612', '613']);
  const clpReading = await reading(clp.id, '0', '3600');
  const pantryReading = await reading(pantry.id, '0', '180');
  await reading(m611.id, '0', '420');
  const groups = [['614'], ['615'], ['616'], ['617', '618', '619', '620', '621', '622'], ['623', '624', '625', '626', '627'], ['628', '629'], ['630'], ['631']];
  const notes: string[] = [];
  for (const g of groups.slice(0, 3)) notes.push((await note(xiaomi.id, g)).id);
  ck('B1 the first three notes take a sixth each of what is left, 3600 - 180 - 420 = 3000', (await Promise.all(notes.map(elecTotal))).join(' ') === '500.00 500.00 500.00');
  const partly = await listed(clpReading.id);
  ck('B2 the reading reads as billed in part, on those three notes, the other fifteen units named', partly.billing === 'PARTIAL' && partly.billedOn.length === 3 && partly.unbilledUnits.length === 15 && partly.unbilledLabel === '617–631' && partly.blockedBy === null,
    JSON.stringify({ billing: partly.billing, notes: partly.billedOn.length, unbilled: partly.unbilledLabel, blockedBy: partly.blockedBy }));
  for (const g of groups.slice(3)) notes.push((await note(xiaomi.id, g)).id);
  const totals = await Promise.all(notes.map(elecTotal));
  ck('B3 each note bills its own share', totals.join(' ') === '500.00 500.00 500.00 500.00 500.00 166.67 166.66 166.67', totals.join(' '));
  ck('B4 and the eight add up to the meter to the cent', sum(totals).toFixed(2) === '3000.00', sum(totals).toFixed(2));
  const full = await listed(clpReading.id);
  ck('B5 the reading is billed in full, on all eight notes', full.billing === 'FULL' && full.billedOn.length === 8 && full.unbilledUnits.length === 0, JSON.stringify({ billing: full.billing, notes: full.billedOn.length }));
  const descriptions = (await elecLines(notes[0])).map((l) => l.description).concat((await elecLines(notes[6])).map((l) => l.description), (await elecLines(notes[4])).map((l) => l.description)[0]);
  ck('B6 each line says its part: 1/6, 1/18, and a percentage for a share with decimals', descriptions[0].endsWith('1/6)') && descriptions[1].endsWith('1/18)') && descriptions[2].endsWith('3.33%)'), JSON.stringify(descriptions));
  const neighbourNote = await note(neighbour.id);
  ck('B7 611-613 are billed their own sub-meter, evenly', (await elecLines(neighbourNote.id)).map((l) => l.amount.toFixed(2)).join(' ') === '140.00 140.00 140.00');
  const pantryListed = await listed(pantryReading.id);
  ck('B8 the pantry\'s reading, billed to no one, reads as nothing to bill — not as waiting for a lease', pantryListed.billing === 'NOT_BILLABLE' && pantryListed.blockedBy === null,
    JSON.stringify({ billing: pantryListed.billing, blockedBy: pantryListed.blockedBy }));

  console.log('\nC. One meter, two leases — the second is billed too');
  const leaseA = await lease('A', ['S1']);
  const leaseB = await lease('B', ['S2', 'S3']);
  const shared = await api.createMeter({ chargeTypeId: elec.id, serialNo: 'ZZ-MSH-SHARED', unitIds: [u.S1, u.S2, u.S3] });
  const sharedReading = await reading(shared.id, '0', '900');
  const noteA = await note(leaseA.id);
  const noteB = await note(leaseB.id);
  ck('C1 the first lease bills a third', (await elecTotal(noteA.id)) === '300.00');
  ck('C2 and the second its two thirds, where it used to bill nothing', (await elecTotal(noteB.id)) === '600.00');
  ck('C3 the reading is billed in full', (await listed(sharedReading.id)).billing === 'FULL');

  console.log('\nD. Undoing a note gives back its own shares and no others');
  await billing.voidInvoice({ organizationId: orgId, invoiceId: noteB.id });
  const afterVoid = await listed(sharedReading.id);
  ck('D1 voiding the second note leaves the first lease\'s third billed', afterVoid.billing === 'PARTIAL' && afterVoid.unbilledUnits.join(',') === 'S2,S3', JSON.stringify(afterVoid.unbilledUnits));
  const noteB2 = await note(leaseB.id);
  ck('D2 a new note bills the two thirds again', (await elecTotal(noteB2.id)) === '600.00');
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: noteB2.id });
  ck('D3 rebuilding it keeps them, without tripping over its own claims', (await elecTotal(noteB2.id)) === '600.00' && (await listed(sharedReading.id)).billing === 'FULL');
  const s3Line = (await elecLines(noteB2.id)).find((l) => l.description.includes('S3'))!;
  await billing.removeLine({ organizationId: orgId, lineId: s3Line.id });
  const afterRemove = await listed(sharedReading.id);
  ck('D4 taking one unit\'s line off releases that unit\'s share only', afterRemove.billing === 'PARTIAL' && afterRemove.unbilledUnits.join(',') === 'S3', JSON.stringify(afterRemove.unbilledUnits));
  const s3Note = await note(leaseB.id, ['S3']);
  ck('D5 and a note for that unit bills it', (await elecTotal(s3Note.id)) === '300.00' && (await listed(sharedReading.id)).billing === 'FULL');

  console.log('\nE. A unit with no share needs no note');
  const leaseC = await lease('C', ['S4', 'S5']);
  const zeroed = await api.createMeter({ chargeTypeId: elec.id, serialNo: 'ZZ-MSH-ZERO', unitIds: [u.S4, u.S5], shares: { [u.S4]: '2', [u.S5]: '0' } });
  const zeroReading = await reading(zeroed.id, '0', '250');
  const noteC = await note(leaseC.id);
  ck('E1 the unit with a share takes the whole meter, the other no line', (await elecLines(noteC.id)).map((l) => `${l.description.split(' · ')[1].split(' ')[0]}=${l.amount.toFixed(2)}`).join(' ') === 'S4=250.00');
  ck('E2 and the reading is billed in full', (await listed(zeroReading.id)).billing === 'FULL');

  console.log('\nF. What nobody can bill yet is named');
  const leaseD = await lease('D', ['S6']);
  const vacant = await api.createMeter({ chargeTypeId: elec.id, serialNo: 'ZZ-MSH-VACANT', unitIds: [u.S6, u.S7] });
  const vacantReading = await reading(vacant.id, '0', '100');
  await note(leaseD.id);
  const held = await listed(vacantReading.id);
  ck('F1 half billed, and the empty unit\'s half is held for want of a lease', held.billing === 'PARTIAL' && held.unbilledUnits.join(',') === 'S7' && held.blockedBy === 'NO_LEASE', JSON.stringify({ billing: held.billing, unbilled: held.unbilledUnits, blockedBy: held.blockedBy }));
  await api.updateMeter({ id: vacant.id, shares: { [u.S7]: '0' } });
  ck('F2 giving that unit no share settles the reading', (await listed(vacantReading.id)).billing === 'FULL');

  console.log('\nG. The eight notes every month, from the lease\'s billing groups');
  for (const [i, g] of groups.entries()) {
    await prisma.leaseUnit.updateMany({ where: { leaseId: xiaomi.id, unitId: { in: g.map((n) => u[n]) } }, data: { billingGroup: String(i + 1) } });
  }
  const leaseApi = leasesRouter.createCaller({ ...staffCtx(orgId), user: { ...staffCtx(orgId).user, permissions: ['lease.read', 'invoice.read'] } } as unknown as Context);
  const groupsRead = (await leaseApi.get({ id: xiaomi.id })).billingGroups;
  ck('G1 the lease reads back each unit\'s group', Object.keys(groupsRead).length === 18 && groupsRead[u['617']] === '4' && groupsRead[u['631']] === '8', JSON.stringify(groupsRead).slice(0, 80));
  const feb = (meterId: string, start: string, end: string) =>
    prisma.meterReading.create({
      data: { meterId, readingStart: start, readingEnd: end, periodStart: new Date('2020-02-01'), periodEnd: new Date('2020-02-29'), grossAmount: new Decimal(end).minus(start).toFixed(2), status: 'CONFIRMED' },
    });
  await feb(clp.id, '3600', '7200');
  await feb(pantry.id, '180', '360');
  await feb(m611.id, '420', '840');
  const marchNotes = () => prisma.invoice.findMany({ where: { leaseId: xiaomi.id, billingPeriod: '2020-03', status: { not: 'VOID' } }, select: { id: true, unitScope: true } });
  await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-03' });
  const march = await marchNotes();
  const marchTotals = (await Promise.all(march.map((n) => elecTotal(n.id)))).sort();
  ck('G2 the monthly run raises one note per group, not one for the whole lease', march.length === 8 && march.every((n) => Array.isArray(n.unitScope)), `${march.length} notes`);
  ck('G3 each with its group\'s share of the month', marchTotals.join(' ') === '166.66 166.67 166.67 500.00 500.00 500.00 500.00 500.00', marchTotals.join(' '));
  await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-03' });
  ck('G4 running it again raises nothing more', (await marchNotes()).length === 8);
  const group4 = march.find((n) => (n.unitScope as string[]).includes(u['617']))!;
  const invoiceApi = invoicesRouter.createCaller({ ...staffCtx(orgId), user: { ...staffCtx(orgId).user, permissions: ['invoice.read'] } } as unknown as Context);
  ck('G5 the list names the units a note bills', (await invoiceApi.list()).find((i) => i.id === group4.id)?.units === '617–622');
  await billing.voidInvoice({ organizationId: orgId, invoiceId: group4.id });
  const again = await billing.generateGroupDrafts({ organizationId: orgId, leaseId: xiaomi.id, period: '2020-03' });
  ck('G6 after voiding one, raising the groups again raises that one only', again.created === 1 && again.skipped === 7 && (await marchNotes()).length === 8, JSON.stringify(again));
  ck('G7 with every unit already on a note, there is nothing to raise', JSON.stringify(await billing.generateGroupDrafts({ organizationId: orgId, leaseId: xiaomi.id, period: '2020-03' })) === JSON.stringify({ created: 0, skipped: 8 }));
  // 1000 over 18 units by groups of 1, 1, 1, 6, 5, 2, 1, 1: rounded note by note
  // it came to 1000.02.
  const mgmt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'MGMT', nameEn: 'Management fee', category: 'RECURRING' } });
  await prisma.chargeRule.create({ data: { leaseId: xiaomi.id, chargeTypeId: mgmt.id, amount: '1000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 } });
  await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-04' });
  const aprilFees = (await prisma.invoiceLine.findMany({ where: { chargeTypeId: mgmt.id, invoice: { leaseId: xiaomi.id, billingPeriod: '2020-04' } }, select: { amount: true } })).map((l) => l.amount.toString());
  ck('G8 a charge for the whole lease, shared over the eight notes, adds up to its amount to the cent', aprilFees.length === 8 && sum(aprilFees).toFixed(2) === '1000.00', `${aprilFees.length} lines, ${sum(aprilFees).toFixed(2)}`);
}

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  const invoices = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invoices } } });
  await prisma.invoice.deleteMany({ where: { id: { in: invoices } } });
  const journal = (await prisma.journalEntry.findMany({ where, select: { id: true } })).map((e) => e.id);
  await prisma.journalLine.deleteMany({ where: { entryId: { in: journal } } });
  await prisma.journalEntry.updateMany({ where: { id: { in: journal } }, data: { reversesId: null } });
  await prisma.journalEntry.deleteMany({ where: { id: { in: journal } } });
  const meters = (await prisma.meter.findMany({ where: { chargeType: where }, select: { id: true } })).map((m) => m.id);
  await prisma.meterReading.deleteMany({ where: { meterId: { in: meters } } });
  await prisma.meter.updateMany({ where: { id: { in: meters } }, data: { parentMeterId: null } });
  await prisma.meterUnit.deleteMany({ where: { meterId: { in: meters } } });
  await prisma.meter.deleteMany({ where: { id: { in: meters } } });
  const leases = (await prisma.lease.findMany({ where, select: { id: true } })).map((l) => l.id);
  await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leases } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leases } } });
  await prisma.lease.deleteMany({ where: { id: { in: leases } } });
  const props = (await prisma.property.findMany({ where, select: { id: true } })).map((p) => p.id);
  await prisma.utilityTariff.deleteMany({ where: { propertyId: { in: props } } });
  await prisma.unit.deleteMany({ where: { propertyId: { in: props } } });
  await prisma.property.deleteMany({ where: { id: { in: props } } });
  await prisma.tenant.deleteMany({ where });
  await prisma.chargeType.deleteMany({ where });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function cleanup() {
  try { await purge(); 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); });
