/**
 * Functional smoke for settlement methods.
 *
 * Two defects, one feature.
 *
 * The defects: only the deposit-refund path validated the method at all. Both
 * receipt paths wrote `input.settlementMethodId ?? null` straight onto the row,
 * so a payment could be recorded against a deactivated method, or against a
 * cheque with no cheque number — the one thing that makes a cheque traceable
 * afterwards. A and B below fail on two of three paths before the change.
 *
 * The feature: methods were seed-only. Adding PayMe or retiring one meant
 * editing seed.ts and re-running it. There is no delete — Receipt is
 * onDelete: SetNull, so deleting a method blanks how every past payment was
 * made — so deactivating has to keep working for the records that name it,
 * which is what C asserts.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/settlement-method-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 { 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 { ReportsService } from '../src/reports/reports.service';
import { configRouter } from '../src/trpc/routers/config.router';
import { settlementMethodsRouter } from '../src/trpc/routers/settlement-methods.router';
import type { AuthUser } from '../src/trpc/auth-user';
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 = 'ZZSMT';

const prisma = new PrismaService();
const ledger = new LedgerService();
const numbers = new NumberService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, numbers, new EventEmitter2(), approvals);
const payments = new PaymentsService(prisma, ledger, numbers, new EventEmitter2());
const deposits = new DepositsService(prisma, ledger, numbers, approvals);
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 REF = 'ZZ-SM';
const PROP = 'ZZ SM Property';
const TENANT = 'ZZ SM Tenant';
const CODES = ['ZZ_CASH', 'ZZ_CHEQUE', 'ZZ_NEW'];

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

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

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 perms = ['settlement-method.read', 'settlement-method.create', 'settlement-method.update', 'charge-type.read'];
  const admin = settlementMethodsRouter.createCaller(staffCtx(orgId, perms));
  const config = configRouter.createCaller(staffCtx(orgId, perms));

  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 SM 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: '9000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
    },
  });
  const mkInvoice = async (period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period });
    await issueInvoice(deps, orgId, inv.id);
    return inv.id;
  };

  console.log('A. A method that needs a reference is refused without one — on every path');
  const cheque = await admin.create({ code: 'ZZ_CHEQUE', nameEn: 'ZZ Cheque', requiresReference: true, sortOrder: 900, isActive: true });
  const inv1 = await mkInvoice('2019-01');
  const noRef = await refused(() =>
    payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: inv1, amount: '100', settlementMethodId: cheque.id }),
  );
  ck('A1 submitReceipt refuses it', noRef.includes('reference is required'), `got "${noRef}"`);
  const noRefBulk = await refused(() =>
    payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '100', settlementMethodId: cheque.id, allocations: [{ invoiceId: inv1, amount: '100' }] }),
  );
  ck('A2 recordBulkPayment refuses it', noRefBulk.includes('reference is required'), `got "${noRefBulk}"`);

  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '1000' });
  await deposits.settle({ organizationId: orgId, depositId: dep.id });
  const noRefRefund = await refused(() =>
    deposits.disburseRefund({ organizationId: orgId, depositId: dep.id, settlementMethodId: cheque.id }),
  );
  ck('A3 disburseRefund refuses it', noRefRefund.includes('reference is required'), `got "${noRefRefund}"`);

  const ok = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '100',
    settlementMethodId: cheque.id, reference: 'ZZ-CHQ-001', allocations: [{ invoiceId: inv1, amount: '100' }],
  });
  ck('A4 and accepted once a reference is given', Boolean(ok.id));
  await payments.approve({ organizationId: orgId, receiptId: ok.id });

  console.log('');
  console.log('B. A deactivated method is out of circulation everywhere');
  const cash = await admin.create({ code: 'ZZ_CASH', nameEn: 'ZZ Cash', requiresReference: false, sortOrder: 901, isActive: true });
  await admin.setActive({ id: cash.id, isActive: false });
  const dead = await refused(() =>
    payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '50', settlementMethodId: cash.id, allocations: [{ invoiceId: inv1, amount: '50' }] }),
  );
  ck('B1 a payment cannot be recorded against it', dead.includes('not found'), `got "${dead}"`);
  const deadRefund = await refused(() => deposits.disburseRefund({ organizationId: orgId, depositId: dep.id, settlementMethodId: cash.id }));
  ck('B2 nor a refund paid with it', deadRefund.includes('not found'), `got "${deadRefund}"`);

  // The read-path split is the whole point of the switch: gone from the
  // pickers, still on the screen that manages them.
  const picker = await config.settlementMethods();
  ck('B3 it is gone from the pickers', !picker.some((m) => m.id === cash.id));
  const managed = await admin.list();
  ck('B4 but still on the management screen', managed.some((m) => m.id === cash.id), 'a retired method that vanishes cannot be brought back');

  console.log('');
  console.log('C. Retiring a method does not rewrite history');
  await admin.setActive({ id: cheque.id, isActive: false });
  const receipts = await prisma.receipt.findMany({ where: { id: ok.id }, include: { settlementMethod: { select: { nameEn: true } } } });
  ck('C1 a receipt taken with it still names it', receipts[0]?.settlementMethod?.nameEn === 'ZZ Cheque', `got ${receipts[0]?.settlementMethod?.nameEn}`);
  const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });
  const collections = await reports.collections(orgId, today, today);
  const bucketed = collections.groups.flatMap((g) => g.methods).some((m) => m.method === 'ZZ Cheque');
  ck('C2 and collections still buckets it by name, not "Unspecified"', bucketed, JSON.stringify(collections.groups.flatMap((g) => g.methods.map((m) => m.method))));
  await admin.setActive({ id: cheque.id, isActive: true });

  console.log('');
  console.log('D. The management screen itself');
  const dup = await refused(() => admin.create({ code: 'ZZ_CHEQUE', nameEn: 'ZZ Dup', requiresReference: false, sortOrder: 902, isActive: true }));
  ck('D1 a duplicate code is refused with a sentence', dup.includes('already exists'), `got "${dup}"`);
  await admin.update({ id: cheque.id, nameEn: 'ZZ Cheque Renamed', nameZh: '支票', requiresReference: true, sortOrder: 900, isActive: true });
  const renamed = (await admin.list()).find((m) => m.id === cheque.id);
  ck('D2 a rename lands', renamed?.nameEn === 'ZZ Cheque Renamed');
  ck('D3 the code is unchanged — records already refer to it', renamed?.code === 'ZZ_CHEQUE');
  ck('D4 usage is reported, so retiring one is an informed choice', (renamed?.receiptCount ?? 0) >= 1, `got ${renamed?.receiptCount}`);
  const lowered = await admin.create({ code: 'zz_new', nameEn: 'ZZ New', requiresReference: false, sortOrder: 903, isActive: true });
  ck('D5 a code is stored upper-case', (await admin.list()).find((m) => m.id === lowered.id)?.code === 'ZZ_NEW');
}

async function purgeStale() {
  const tenants = await prisma.tenant.findMany({ where: { name: TENANT }, select: { id: true } });
  const tenantIds = tenants.map((t) => t.id);
  if (tenantIds.length) {
    const depIds = (await prisma.deposit.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } })).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(() => {});
      await removeEntries(depIds);
    }
    const rIds = (await prisma.receipt.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } })).map((r) => r.id);
    if (rIds.length) {
      await prisma.receiptAllocationItem.deleteMany({ where: { allocation: { receiptId: { in: rIds } } } }).catch(() => {});
      await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rIds } } });
      await removeEntries(rIds);
      await prisma.receipt.deleteMany({ where: { id: { in: rIds } } });
    }
    await prisma.deposit.deleteMany({ where: { tenantId: { in: tenantIds } } });
  }
  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) {
      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: 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: 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 } });
  await prisma.settlementMethod.deleteMany({ where: { code: { in: CODES } } }).catch(() => {});
}

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

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