/**
 * Functional smoke for what the tenant portal says is owed.
 *
 * The portal used to report the SUM OF THE LINES as both the summary balance and
 * the amount owed on a note. That is the face value, not the debt: once the
 * office approves a part payment, or applies a deposit to arrears, the ledger
 * says one thing and the portal says another. It matters because the payment
 * form is prefilled from that figure and submitReceipt refuses anything above
 * the real outstanding — so every tenant with a part-paid note pressed Submit
 * and got an error, with no figure anywhere telling them what to type instead.
 *
 * Asserts the portal's three figures against the ledger through a part payment
 * and a deposit application. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/portal-outstanding-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma } from '@prisma/client';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { invoiceArState } from '../src/billing/invoice-ar';
import { NumberService } from '../src/common/number.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { portalRouter } from '../src/trpc/routers/portal.router';
import type { Context } from '../src/trpc/trpc';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

/** This smoke's own landlord company (see _smoke-company.ts). */
const LANDLORD = 'ZZPOR';

const prisma = new PrismaService();
const ledger = new LedgerService();
const numbers = new NumberService();
const events = new EventEmitter2();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, numbers, events, approvals);
const payments = new PaymentsService(prisma, ledger, numbers, events);
const deposits = new DepositsService(prisma, ledger, numbers, approvals);
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 REF = 'ZZ-POR';
const PROP = 'ZZ Portal Property';
const TENANT = 'ZZ Portal Tenant';

/** The ledger's own answer, which the portal must agree with. */
const owed = async (orgId: string, invoiceId: string) =>
  (await invoiceArState(prisma as unknown as Prisma.TransactionClient, orgId, invoiceId)).outstanding.toFixed(2);

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 tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: PROP, units: { create: [{ name: 'ZZ Por A' }] } },
    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('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: property.units[0].id }] },
      chargeRules: { create: [
        { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
      ] },
    },
  });

  const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  await issueInvoice(deps, orgId, inv.id);

  console.log('A. Nothing paid yet — the face value IS what is owed');
  ck('A1 the ledger says the whole amount', (await owed(orgId, inv.id)) === '10000.00');

  console.log('');
  console.log('B. A part payment is approved');
  const receipt = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '4000',
    allocations: [{ invoiceId: inv.id, amount: '4000' }],
  });
  await payments.approve({ organizationId: orgId, receiptId: receipt.id });
  ck('B1 the ledger now says 6000', (await owed(orgId, inv.id)) === '6000.00', `got ${await owed(orgId, inv.id)}`);
  const afterPart = await prisma.invoice.findUniqueOrThrow({ where: { id: inv.id }, select: { status: true } });
  ck('B2 and the note reads PARTIALLY_PAID', afterPart.status === 'PARTIALLY_PAID', `got ${afterPart.status}`);

  console.log('');
  console.log('C. A deposit is applied to the arrears');
  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '1500' });
  await deposits.apply({ organizationId: orgId, depositId: dep.id, invoiceId: inv.id, amount: '1500' });
  ck('C1 the ledger now says 4500', (await owed(orgId, inv.id)) === '4500.00', `got ${await owed(orgId, inv.id)}`);

  console.log('');
  console.log('D. The portal must say the same thing the ledger does');
  // Exactly what portal.invoice, portal.invoices and portal.summary compute.
  const faceValue = (await prisma.invoiceLine.findMany({ where: { invoiceId: inv.id }, select: { amount: true } }))
    .reduce((s, l) => s + Number(l.amount), 0)
    .toFixed(2);
  const ledgerOwed = await owed(orgId, inv.id);
  ck('D1 the face value and the debt really have diverged', faceValue === '10000.00' && ledgerOwed === '4500.00', `face ${faceValue}, owed ${ledgerOwed}`);

  const portal = asTenant(orgId, tenant.id);
  const detail = await portal.invoice({ id: inv.id });
  ck('D2 the detail still shows what was charged', detail.total === faceValue, `got ${detail.total}`);
  ck('D3 and separately what is left to pay', detail.outstanding === ledgerOwed, `got ${detail.outstanding} — the payment form is prefilled from this`);

  const list = await portal.invoices();
  const row = list.find((r) => r.id === inv.id);
  ck('D4 the list shows the outstanding, not the face value', row?.outstanding === ledgerOwed, `got ${row?.outstanding}`);

  const sum = await portal.summary();
  ck('D5 the home balance is the outstanding', sum.outstanding[0]?.amount === ledgerOwed, `got ${JSON.stringify(sum.outstanding)}`);

  console.log('');
  console.log('E. The amount the portal offers is one the server will accept');
  // The whole point: submitting the prefilled figure must not be refused.
  const ok = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: detail.outstanding,
    allocations: [{ invoiceId: inv.id, amount: detail.outstanding }],
  });
  ck('E1 paying exactly the offered amount is accepted', Boolean(ok.id));
  await payments.approve({ organizationId: orgId, receiptId: ok.id });
  ck('E2 and it settles the note', (await owed(orgId, inv.id)) === '0.00', `got ${await owed(orgId, inv.id)}`);
  const settled = await prisma.invoice.findUniqueOrThrow({ where: { id: inv.id }, select: { status: true } });
  ck('E3 which now reads PAID', settled.status === 'PAID', `got ${settled.status}`);

  const sum2 = await portal.summary();
  ck('E4 and it drops off the tenant’s balance entirely', sum2.outstanding.length === 0, `got ${JSON.stringify(sum2.outstanding)}`);
}

/** The real portal router, called as the logged-in tenant would reach it. Going
 * through the router (not a local re-implementation) is the point: if it ever
 * goes back to reporting the sum of the lines, D2-D5 go red. */
function asTenant(orgId: string, tenantId: string) {
  const ctx = {
    prisma,
    organizationId: orgId,
    user: { id: `zz-portal-${tenantId}`, email: 'zz@rms.local', name: 'ZZ', tenantId, permissions: [], roles: [] },
  } as unknown as Context;
  return portalRouter.createCaller(ctx);
}

async function purgeStale() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  const leaseIds = leases.map((l) => l.id);
  const tenants = await prisma.tenant.findMany({ where: { name: TENANT }, select: { id: true } });
  const tenantIds = tenants.map((t) => t.id);

  if (tenantIds.length) {
    const deps2 = await prisma.deposit.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } });
    const depIds = deps2.map((d) => d.id);
    if (depIds.length) {
      await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
      await prisma.depositSettlementLine.deleteMany({ where: { settlement: { depositId: { in: depIds } } } }).catch(() => {});
      await prisma.depositSettlement.deleteMany({ where: { depositId: { in: depIds } } }).catch(() => {});
    }
    const receipts = await prisma.receipt.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } });
    const rIds = receipts.map((r) => r.id);
    if (rIds.length) {
      await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rIds } } });
      await removeEntries(rIds);
    }
    if (depIds.length) await removeEntries(depIds);
  }

  for (const id of leaseIds) {
    const invIds = (await prisma.invoice.findMany({ where: { leaseId: id }, select: { id: true } })).map((i) => i.id);
    if (invIds.length) {
      await removeEntries(invIds);
      await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
      await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    }
    await prisma.leaseUnit.deleteMany({ where: { leaseId: id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: id } });
    await prisma.lease.delete({ where: { id } }).catch(() => {});
  }
  if (tenantIds.length) {
    await prisma.deposit.deleteMany({ where: { tenantId: { in: tenantIds } } });
    await prisma.receipt.deleteMany({ where: { tenantId: { in: tenantIds } } });
  }
  const props = await prisma.property.findMany({ where: { name: PROP }, 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: TENANT } });
}

/** Journal entries for these sources, reversals first so the FK holds. */
async function removeEntries(sourceIds: string[]) {
  const entries = await prisma.journalEntry.findMany({
    where: { OR: [{ sourceId: { in: sourceIds } }, { lines: { some: { invoiceId: { in: sourceIds } } } }] },
    select: { id: true, reversesId: true },
  });
  const eids = entries.map((e) => e.id);
  if (!eids.length) return;
  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 } } });
}

async function cleanup() {
  try { await purgeSmokeApprover(prisma); await purgeSmokeLandlord(prisma, LANDLORD); 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); });
