/**
 * Functional smoke for the outstanding debit notes report and its saved layouts.
 *
 * The report splits each note's receivable by what moved it — charged, brought
 * forward, received, paid from a deposit, carried forward — as at a date, so
 * this proves the split always adds back up to what is owed, that it reads the
 * same ledger AR Aging does (their totals can never disagree), that a reversal
 * counts against what it reversed, and that the settlement filter and the date
 * criteria pick the notes they say. AR Aging itself is a row per lease, with the
 * premises as the debit note prints them, and can be narrowed to tenants. Then
 * the layouts: a person's own are theirs alone, the shared ones everyone's.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/outstanding-report-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } 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 { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import type { OutstandingInvoiceQuery, OutstandingInvoiceRow } from '../src/reports/reports.types';
import { reportsRouter } from '../src/trpc/routers/reports.router';
import type { Context } from '../src/trpc/trpc';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

const LANDLORD = 'ZZOIR';
const PROP = 'ZZ OIR Property';
const TENANT = 'ZZ OIR Tenant';
const REF = 'ZZ-OIR';
const EMAILS = ['zz-oir-1@rms.local', 'zz-oir-2@rms.local'];

const prisma = new PrismaService();
const ledger = new LedgerService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, new NumberService(), new EventEmitter2(), approvals);
const payments = new PaymentsService(prisma, ledger, new NumberService(), new EventEmitter2());
const reports = new ReportsService(prisma);
const deps = { prisma, billing, approvals };

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

const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });
const yesterday = new Date(Date.now() - 86_400_000).toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });
const OWED: OutstandingInvoiceQuery['settlement'] = ['UNSETTLED', 'PARTIAL'];
const ALL: OutstandingInvoiceQuery['settlement'] = ['UNSETTLED', 'PARTIAL', 'SETTLED'];

const run = (q: Partial<OutstandingInvoiceQuery>, orgId: string) =>
  reports.outstandingInvoices(orgId, { asOf: today, settlement: OWED, includeUnissued: false, ...q });
const rowOf = (rows: OutstandingInvoiceRow[], id: string) => rows.find((r) => r.id === id);
/** outstanding = invoiceAmount + broughtForward − received − depositApplied − carriedForward */
const addsUp = (r: OutstandingInvoiceRow) =>
  new Decimal(r.invoiceAmount).plus(r.broughtForward).minus(r.received).minus(r.depositApplied).minus(r.carriedForward).equals(r.outstanding);

function asUser(orgId: string, userId: string) {
  return reportsRouter.createCaller({
    prisma,
    organizationId: orgId,
    reports,
    user: { id: userId, email: 'zz@rms.local', name: 'ZZ', tenantId: null, mustChangePassword: false, permissions: ['finance.report'], roles: [] },
  } as unknown as Context);
}
const errorOf = async (p: Promise<unknown>) => {
  try { await p; return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
};

const invoiceIds: string[] = [];
const receiptIds: string[] = [];

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 landlordId = await smokeLandlord(prisma, orgId, LANDLORD);
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT, nameZh: 'ZZ 租客' } });
  await prisma.tenantCode.create({ data: { organizationId: orgId, tenantId: tenant.id, landlordId, code: 'ZZOIRT01' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId, name: PROP, units: { create: [{ name: 'ZZ O1' }, { name: 'ZZ O2' }] } },
    include: { units: true },
  });
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-1`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2099-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: property.units.map((u) => ({ unitId: u.id })) },
      chargeRules: { create: [{ chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
    },
  });
  const issue = async (period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period });
    invoiceIds.push(inv.id);
    await issueInvoice(deps, orgId, inv.id);
    return inv.id;
  };
  const pay = async (invoiceId: string, amount: string) => {
    const r = await payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount, allocations: [{ invoiceId, amount }] });
    receiptIds.push(r.id);
    await payments.approve({ organizationId: orgId, receiptId: r.id });
  };

  const a = await issue('2099-01');
  const b = await issue('2099-02');
  const c = await issue('2099-03');
  await pay(a, '4000');
  await pay(c, '10000');
  console.log('Fixture: three notes of 10,000 — A part paid 4,000, B unpaid, C paid in full\n');

  console.log('S. Settlement, and what each note is made of');
  const owed = await run({}, orgId);
  const ra = rowOf(owed.rows, a), rb = rowOf(owed.rows, b);
  ck('S1 A is partly settled: 10,000 charged, 4,000 received, 6,000 owed',
    ra?.settlement === 'PARTIAL' && ra.invoiceAmount === '10000.00' && ra.received === '4000.00' && ra.outstanding === '6000.00', JSON.stringify(ra && { s: ra.settlement, i: ra.invoiceAmount, r: ra.received, o: ra.outstanding }));
  ck('S2 B is unsettled, owed in full', rb?.settlement === 'UNSETTLED' && rb.outstanding === '10000.00', JSON.stringify(rb?.outstanding));
  ck('S3 C, paid in full, is not among the notes owed', !rowOf(owed.rows, c));
  const all = await run({ settlement: ALL }, orgId);
  const rc = rowOf(all.rows, c);
  ck('S4 asked for, C is there as settled at 0', rc?.settlement === 'SETTLED' && rc.outstanding === '0.00', JSON.stringify(rc?.outstanding));
  ck('S5 every row in the office adds back up to what it owes', all.rows.every(addsUp), JSON.stringify(all.rows.filter((r) => !addsUp(r)).map((r) => r.number)));

  console.log('\nA. It reads the same ledger AR Aging reads');
  const aging = await reports.arAging(orgId, today);
  for (const g of aging.groups) {
    const ours = owed.rows.filter((r) => r.currency === g.currency).reduce((t, r) => t.plus(r.outstanding), new Decimal(0));
    ck(`A1 ${g.currency}: the notes owed total the AR Aging total`, ours.toFixed(2) === g.totals.total, `${ours.toFixed(2)} vs ${g.totals.total}`);
  }

  console.log('\nF. Who and what each note billed');
  ck('F1 tenant, its code under this company, and the company', ra?.tenantName === TENANT && ra.tenantNameZh === 'ZZ 租客' && ra.tenantCode === 'ZZOIRT01' && ra.landlordCode === LANDLORD,
    JSON.stringify(ra && [ra.tenantName, ra.tenantCode, ra.landlordCode]));
  ck('F2 the building and both units', ra?.building === PROP && ra.units === 'ZZ O1, ZZ O2', JSON.stringify(ra && [ra.building, ra.units]));
  ck('F3 the lease and the charge billed', ra?.leaseReference === `${REF}-1` && ra.chargeTypes.length === 1, JSON.stringify(ra?.chargeTypes));
  ck('F4 dates are Hong Kong days', ra?.issueDate === today && /^\d{4}-\d{2}-\d{2}$/.test(ra.dueDate), JSON.stringify(ra && [ra.issueDate, ra.dueDate]));

  console.log('\nD. As at a date, and the date criteria');
  const before = await run({ asOf: yesterday, settlement: ALL }, orgId);
  ck('D1 as at yesterday none of today\'s notes existed', ![a, b, c].some((id) => rowOf(before.rows, id)));
  const feb = await run({ periodFrom: '2099-02', periodTo: '2099-02' }, orgId);
  ck('D2 a billing period range keeps only that period\'s note', !!rowOf(feb.rows, b) && !rowOf(feb.rows, a), feb.rows.filter((r) => r.leaseReference === `${REF}-1`).map((r) => r.billingPeriod).join());
  const due = await run({ dueFrom: rb!.dueDate, dueTo: rb!.dueDate }, orgId);
  ck('D3 a due date range keeps only the notes due in it', !!rowOf(due.rows, b) && !rowOf(due.rows, a));
  const issued = await run({ issueFrom: yesterday, issueTo: yesterday }, orgId);
  ck('D4 an issue date range of yesterday leaves out today\'s notes', !rowOf(issued.rows, a) && !rowOf(issued.rows, b));

  console.log('\nV. A reversal counts against what it reversed');
  await billing.voidInvoice({ organizationId: orgId, invoiceId: b });
  const afterVoid = await run({ settlement: ALL }, orgId);
  ck('V1 a voided note nets to nothing, so it is gone even with settled notes asked for', !rowOf(afterVoid.rows, b));

  console.log('\nC. A carry-forward moves the balance, and an unissued note is opt-in');
  // April's own draft first, so the balance is carried onto a note with charges of its own.
  const draft = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2099-04' });
  invoiceIds.push(draft.id);
  const target = await billing.carryForward({ organizationId: orgId, invoiceId: a, targetPeriod: '2099-04' });
  ck('C0 (the balance went onto that draft)', target.id === draft.id);
  const carried = await run({ settlement: ALL }, orgId);
  const ca = rowOf(carried.rows, a), ct = rowOf(carried.rows, target.id);
  ck('C1 A carried 6,000 forward and now owes nothing', ca?.carriedForward === '6000.00' && ca.outstanding === '0.00' && ca.settlement === 'SETTLED',
    JSON.stringify(ca && [ca.carriedForward, ca.outstanding, ca.settlement]));
  ck('C2 the draft it went onto owes the 6,000 brought forward, though unissued', ct?.broughtForward === '6000.00' && ct.outstanding === '6000.00' && ct.number === null,
    JSON.stringify(ct && [ct.broughtForward, ct.outstanding]));
  const withDrafts = await run({ includeUnissued: true }, orgId);
  const dt = rowOf(withDrafts.rows, target.id);
  ck('C3 with unissued notes asked for, its own 10,000 is owed on top', dt?.invoiceAmount === '10000.00' && dt.outstanding === '16000.00' && dt.status === 'DRAFT',
    JSON.stringify(dt && [dt.invoiceAmount, dt.outstanding, dt.status]));
  ck('C4 and it still adds up', !!dt && addsUp(dt));
  const agingNow = await reports.arAging(orgId, today);
  const owedNow = await run({}, orgId);
  ck('C5 the AR Aging total still agrees', agingNow.groups.every((g) =>
    owedNow.rows.filter((r) => r.currency === g.currency).reduce((t, r) => t.plus(r.outstanding), new Decimal(0)).toFixed(2) === g.totals.total));

  console.log('\nG. AR Aging: a row per lease, with its premises; the tenant filter');
  // Still owed here: the 6,000 carried onto lease 1's April draft. A second
  // lease of the same tenant, on one of the units, owes a note of 10,000.
  await prisma.property.update({ where: { id: property.id }, data: { address: 'ZZ 1 Smoke Road\nNorth Point' } });
  const lease2 = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-2`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2099-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: property.units[1].id }] },
      chargeRules: { create: [{ chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
    },
  });
  const shop = await billing.generateDraft({ organizationId: orgId, leaseId: lease2.id, period: '2099-01' });
  invoiceIds.push(shop.id);
  await issueInvoice(deps, orgId, shop.id);
  const ownOnly = await reports.arAging(orgId, today, [tenant.id]);
  const lines = ownOnly.groups.flatMap((g) => g.rows);
  const at = `${PROP}, ZZ 1 Smoke Road, North Point`;
  ck('G1 asked for one tenant, only its leases are reported, a row each',
    lines.length === 2 && lines.every((r) => r.tenantId === tenant.id && r.tenantName === TENANT), JSON.stringify(lines.map((r) => [r.tenantName, r.leaseReference])));
  ck('G2 the larger debt first, each lease with its own amount', lines[0]?.leaseReference === `${REF}-2` && lines[0].total === '10000.00' && lines[1]?.total === '6000.00',
    JSON.stringify(lines.map((r) => [r.leaseReference, r.total])));
  ck('G3 and its own premises as the debit note prints them: units, building, address',
    lines[0]?.premises === `ZZ O2, ${at}` && lines[1]?.premises === `ZZ O1, ZZ O2, ${at}`, JSON.stringify(lines.map((r) => r.premises)));
  ck('G4 the total is the tenant\'s alone', ownOnly.groups.length === 1 && ownOnly.groups[0].totals.total === '16000.00', JSON.stringify(ownOnly.groups.map((g) => g.totals.total)));
  const everyone = await reports.arAging(orgId, today);
  ck('G5 the tenants to pick from are everyone owing, whoever was asked for',
    JSON.stringify(ownOnly.tenants) === JSON.stringify(everyone.tenants) && everyone.tenants.some((x) => x.id === tenant.id));
  const hkdRows = everyone.groups.find((g) => g.currency === 'HKD')?.rows ?? [];
  const ours = hkdRows.flatMap((r, i) => (r.tenantId === tenant.id ? [i] : []));
  ck('G6 unfiltered, a tenant\'s leases sit together', ours.length === 2 && ours[1] === ours[0] + 1, JSON.stringify(ours));
  const owedLast = await run({}, orgId);
  ck('G7 and the AR Aging total still agrees with the notes owed', everyone.groups.every((g) =>
    owedLast.rows.filter((r) => r.currency === g.currency).reduce((t, r) => t.plus(r.outstanding), new Decimal(0)).toFixed(2) === g.totals.total));
  const viaApi = await asUser(orgId, 'zz-oir-reader').arAging({ asOf: today, tenantIds: [tenant.id] });
  ck('G8 the screen\'s filter reaches the report', viaApi.groups.flatMap((g) => g.rows).length === 2 && viaApi.groups[0]?.totals.total === '16000.00');

  console.log('\nL. Saved layouts: one\'s own, and the office\'s');
  const [u1, u2] = await Promise.all(EMAILS.map((email) => prisma.user.create({ data: { email, name: 'ZZ OIR', passwordHash: 'x' } })));
  const one = asUser(orgId, u1.id), two = asUser(orgId, u2.id);
  const report = 'outstanding-invoices' as const;
  const mine = await one.saveLayout({ report, name: 'ZZ Mine', shared: false, config: { columns: ['number'] } });
  const office = await one.saveLayout({ report, name: 'ZZ Office', shared: true, config: { columns: ['number', 'outstanding'] } });
  const seenByOne = (await one.layouts({ report })).filter((l) => l.name.startsWith('ZZ'));
  const seenByTwo = (await two.layouts({ report })).filter((l) => l.name.startsWith('ZZ'));
  ck('L1 the one who saved them sees both', seenByOne.length === 2, seenByOne.map((l) => l.name).join());
  ck('L2 someone else sees only the shared one', seenByTwo.length === 1 && seenByTwo[0].name === 'ZZ Office' && seenByTwo[0].shared);
  ck('L3 and the config comes back as saved', JSON.stringify(seenByTwo[0]?.config) === JSON.stringify({ columns: ['number', 'outstanding'] }));
  ck('L4 they cannot overwrite another\'s own layout', (await errorOf(two.saveLayout({ id: mine.id, report, name: 'ZZ Taken', shared: false, config: {} }))) === 'Report layout not found');
  ck('L5 nor delete it', (await errorOf(two.deleteLayout({ id: mine.id }))) === 'Report layout not found');
  ck('L6 a second shared layout of the same name is refused', (await errorOf(two.saveLayout({ report, name: 'ZZ Office', shared: true, config: {} }))) === 'A layout with that name already exists');
  ck('L7 but a personal one of that name is fine', (await errorOf(two.saveLayout({ report, name: 'ZZ Office', shared: false, config: {} }))) === '');
  await two.saveLayout({ id: office.id, report, name: 'ZZ Office', shared: true, config: { columns: ['tenantName'] } });
  const updated = (await one.layouts({ report })).find((l) => l.id === office.id);
  ck('L8 anyone may keep the shared one up to date', JSON.stringify(updated?.config) === JSON.stringify({ columns: ['tenantName'] }));
  await one.saveLayout({ id: office.id, report, name: 'ZZ Office', shared: false, config: { columns: ['tenantName'] } });
  ck('L9 un-sharing it makes it the un-sharer\'s alone', !(await two.layouts({ report })).some((l) => l.id === office.id));
  await two.deleteLayout({ id: (await two.layouts({ report })).find((l) => l.name === 'ZZ Office')!.id });
  ck('L10 one\'s own can be deleted', !(await two.layouts({ report })).some((l) => l.name === 'ZZ Office'));
}

/** Leftovers of a run that died before cleaning up. */
async function purgeStale() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  const ids = (await prisma.invoice.findMany({ where: { leaseId: { in: leases.map((l) => l.id) } }, select: { id: true } })).map((i) => i.id);
  const tenants = (await prisma.tenant.findMany({ where: { name: TENANT }, select: { id: true } })).map((t) => t.id);
  const receipts = (await prisma.receipt.findMany({ where: { tenantId: { in: tenants } }, select: { id: true } })).map((r) => r.id);
  await purgeRows(ids, receipts, leases.map((l) => l.id));
}

async function purgeRows(ids: string[], receipts: string[], leaseIds: string[]) {
  const src = [...ids, ...receipts];
  if (src.length) {
    const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: src } }, { lines: { some: { invoiceId: { in: ids } } } }] }, select: { id: true, reversesId: true } });
    const eids = entries.map((e) => e.id);
    if (eids.length) {
      await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
      const reversers = entries.filter((e) => e.reversesId).map((e) => e.id);
      if (reversers.length) await prisma.journalEntry.deleteMany({ where: { id: { in: reversers } } });
      await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
    }
  }
  if (receipts.length) {
    await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: receipts } } });
    await prisma.receipt.deleteMany({ where: { id: { in: receipts } } });
  }
  if (ids.length) {
    await prisma.receiptAllocationItem.deleteMany({ where: { invoiceId: { in: ids } } });
    await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
  }
  await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  const props = await prisma.property.findMany({ where: { name: PROP }, select: { id: true } });
  await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
  await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
  await prisma.tenant.deleteMany({ where: { name: TENANT } }); // its code goes with it
  await prisma.user.deleteMany({ where: { email: { in: EMAILS } } }); // and their layouts with them
  await prisma.reportLayout.deleteMany({ where: { ownerId: null, name: { startsWith: 'ZZ ' } } });
  await purgeSmokeLandlord(prisma, LANDLORD);
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  try {
    const leases = (await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } })).map((l) => l.id);
    await purgeRows(invoiceIds, receiptIds, leases);
    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); });
