/**
 * Functional smoke for the payee printed on a debit note.
 *
 * The template has always printed "pay by crossed cheque made payable to
 * {{payee.accountName}}" plus bank name and account number, resolved from
 * invoice.payeeSnapshot → invoice.bankAccount → the organisation's collection
 * account. All three were unreachable: nothing could create a BankAccount (no
 * router, no screen, no seed row) and payeeSnapshot was never written by
 * anything. Every document fell through to accountName = the org's own name
 * with a blank bank and a blank account number, and the tenant portal served
 * the same PDF.
 *
 * The behaviour that matters and is easy to lose: the payee is FROZEN when the
 * note is issued. Re-printing a note from two years ago must show the account
 * it was issued with, not the one the company banks with today.
 *
 * It runs in its own organisation. What is under test is the organisation's
 * DEFAULT account, and there is only one: in an org that already has its own
 * default set — UAT does — the real account wins the tie and every assertion
 * about "the default" ends up checking somebody else's bank details.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/bank-account-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
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 { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), 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-BNK';
const ORG_CODE = `${REF}-ORG`;
const PROP = 'ZZ Bank Property';
const TENANT = 'ZZ Bank Tenant';
const ACC = 'ZZ Bank ';

type Snap = { accountName?: string; bankName?: string; accountNumber?: string } | null;
const snapOf = async (invoiceId: string): Promise<Snap> =>
  (await prisma.invoice.findUniqueOrThrow({ where: { id: invoiceId }, select: { payeeSnapshot: true } })).payeeSnapshot as Snap;

async function main() {
  await purgeStale();

  // An empty org has no approval workflow, so a note issues straight away.
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Bank smoke org' } })).id;
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZZBNK-', padding: 5 } });
  await prisma.glAccount.create({ data: { organizationId: orgId, code: '1100', name: 'Accounts Receivable', type: 'ASSET', role: 'RECEIVABLE' } });
  const income = await prisma.glAccount.create({ data: { organizationId: orgId, code: '4000', name: 'Rental Income', type: 'INCOME' } });
  const rentCt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: income.id } });

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: PROP, units: { create: [{ name: 'ZZ Bnk A' }] } },
    include: { units: true },
  });

  const mkLease = (suffix: string, start: string, bankAccountId: string | null) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `${REF}-${suffix}`, tenantId: tenant.id,
        status: 'ACTIVE', currency: 'HKD', startDate: new Date(start), endDate: new Date('2100-01-01'),
        depositMonths: 0, bankAccountId,
        units: { create: [{ unitId: property.units[0].id }] },
        chargeRules: { create: [{ chargeTypeId: rentCt.id, amount: '9000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
      },
    });

  const mkAccount = (name: string, bankName: string, accountNumber: string, isCollectionAgent = false) =>
    prisma.bankAccount.create({
      data: { organizationId: orgId, name: ACC + name, bankName, accountName: `ZZ Holdings ${name}`, accountNumber, isCollectionAgent, isActive: true },
    });

  console.log('A. The organisation default is what a plain lease collects into');
  const main1 = await mkAccount('Main', 'ZZ Bank HK', '111-222-333', true);
  const leaseA = await mkLease('A', '2019-01-01', null);
  const invA = await billing.generateDraft({ organizationId: orgId, leaseId: leaseA.id, period: '2019-01' });
  ck('A1 a draft has no payee frozen yet', (await snapOf(invA.id)) === null);
  await billing.issue({ organizationId: orgId, invoiceId: invA.id });
  const snapA = await snapOf(invA.id);
  ck('A2 issuing freezes the default account', snapA?.accountNumber === '111-222-333', `got ${JSON.stringify(snapA)}`);
  ck('A3 with the name the tenant writes the cheque to', snapA?.accountName === 'ZZ Holdings Main');
  ck('A4 and the bank', snapA?.bankName === 'ZZ Bank HK');
  const linked = await prisma.invoice.findUniqueOrThrow({ where: { id: invA.id }, select: { bankAccountId: true } });
  ck('A5 the note also records which account that was', linked.bankAccountId === main1.id);

  console.log('');
  console.log('B. A lease with its own account overrides the default');
  const other = await mkAccount('Client', 'ZZ Bank SG', '999-888-777');
  const leaseB = await mkLease('B', '2019-02-01', other.id);
  const invB = await billing.generateDraft({ organizationId: orgId, leaseId: leaseB.id, period: '2019-02' });
  await billing.issue({ organizationId: orgId, invoiceId: invB.id });
  const snapB = await snapOf(invB.id);
  ck('B1 the lease’s own account is used', snapB?.accountNumber === '999-888-777', `got ${JSON.stringify(snapB)}`);
  ck('B2 not the organisation default', snapB?.accountName === 'ZZ Holdings Client');

  console.log('');
  console.log('C. Changing the account later does not rewrite an issued note');
  // The company moves banks. Every note issued before today must keep saying
  // where it said to pay, or a tenant reconciling an old note is misled.
  await prisma.bankAccount.update({ where: { id: main1.id }, data: { bankName: 'ZZ Bank NEW', accountNumber: '444-555-666' } });
  const stillA = await snapOf(invA.id);
  ck('C1 the old note keeps the details it was issued with', stillA?.accountNumber === '111-222-333', `got ${stillA?.accountNumber}`);
  ck('C2 including the bank name', stillA?.bankName === 'ZZ Bank HK');

  const leaseC = await mkLease('C', '2019-03-01', null);
  const invC = await billing.generateDraft({ organizationId: orgId, leaseId: leaseC.id, period: '2019-03' });
  await billing.issue({ organizationId: orgId, invoiceId: invC.id });
  ck('C3 a note issued after the change gets the new details', (await snapOf(invC.id))?.accountNumber === '444-555-666');

  console.log('');
  console.log('D. Deactivating the default hands over to the next one');
  await prisma.bankAccount.update({ where: { id: main1.id }, data: { isActive: false } });
  await prisma.bankAccount.update({ where: { id: other.id }, data: { isCollectionAgent: true } });
  const leaseD = await mkLease('D', '2019-04-01', null);
  const invD = await billing.generateDraft({ organizationId: orgId, leaseId: leaseD.id, period: '2019-04' });
  await billing.issue({ organizationId: orgId, invoiceId: invD.id });
  ck('D1 a deactivated account is not used for new notes', (await snapOf(invD.id))?.accountNumber === '999-888-777', `got ${JSON.stringify(await snapOf(invD.id))}`);

  console.log('');
  console.log('E. With no account at all, issuing still works');
  // It must not become a hard failure — that would stop billing entirely on a
  // fresh install. The document simply falls back, which is what the warning on
  // the bank accounts page is for.
  await prisma.bankAccount.updateMany({ where: { organizationId: orgId, name: { startsWith: ACC } }, data: { isActive: false } });
  const leaseE = await mkLease('E', '2019-05-01', null);
  const invE = await billing.generateDraft({ organizationId: orgId, leaseId: leaseE.id, period: '2019-05' });
  let threw = '';
  try {
    await billing.issue({ organizationId: orgId, invoiceId: invE.id });
  } catch (e) {
    threw = e instanceof Error ? e.message : String(e);
  }
  ck('E1 issuing is not blocked by having no bank account', threw === '', threw);
  const issuedE = await prisma.invoice.findUniqueOrThrow({ where: { id: invE.id }, select: { status: true } });
  ck('E2 and the note is issued', issuedE.status === 'ISSUED', `got ${issuedE.status}`);
}

async function purgeStale() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, 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, reversesId: true },
      });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        const rev = entries.filter((e) => e.reversesId).map((e) => e.id);
        if (rev.length) await prisma.journalEntry.deleteMany({ where: { id: { in: rev } } });
        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(() => {});
  }
  await prisma.bankAccount.deleteMany({ where: { name: { startsWith: ACC } } }).catch(() => {});
  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 } });
  // 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.chargeType.deleteMany({ where: { organizationId: org.id } });
    await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
    await prisma.numberSequence.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); });
