/**
 * Functional smoke test for the invoice→deposit auto-link. Standalone (writes to
 * the dev DB, self-cleans). Proves: paying a deposit-charge invoice auto-creates a
 * managed Deposit, the Deposits-Held (2300) liability is NOT double-counted, the
 * held balance reads correctly, and applying the deposit works.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/deposit-link-smoke.ts
 */
import 'reflect-metadata';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } from '@rms/domain';
import { BillingService } from '../src/billing/billing.service';
import { ApprovalService } from '../src/approvals/approval.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PaymentsService } from '../src/payments/payments.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

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

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

const createdInvoiceIds: string[] = [];
const createdReceiptIds: string[] = [];
let fx: { tenantId: string; propertyId: string; unitId: string; leaseId: string } | null = null;
let autoDepositId: string | null = null;

async function held2300(orgId: string): Promise<Decimal> {
  const acc = await prisma.glAccount.findFirst({ where: { organizationId: orgId, role: 'DEPOSITS_HELD' } });
  if (!acc) return new Decimal(0);
  const lines = await prisma.journalLine.findMany({ where: { accountId: acc.id }, select: { direction: true, amount: true } });
  let cr = new Decimal(0), dr = new Decimal(0);
  for (const l of lines) l.direction === 'CREDIT' ? (cr = cr.plus(l.amount.toString())) : (dr = dr.plus(l.amount.toString()));
  return cr.minus(dr); // liability = CR − DR
}

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('No org seeded');
  const orgId = org.id;
  const depCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'DEPOSIT', glAccountId: { not: null }, isActive: true }, select: { id: true, nameEn: true } });
  const rentCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'RECURRING', glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!depCt || !rentCt) throw new Error('Need a DEPOSIT and a RECURRING charge type with GL accounts');

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Dep Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Dep Property', units: { create: { name: 'ZZ DU1' } } }, include: { units: true } });
  const unit = property.units[0];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-DEP-${property.id.slice(-5)}`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: { unitId: unit.id } },
      chargeRules: {
        create: [
          { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
          { chargeTypeId: depCt.id, amount: '36000', frequencyMonths: 0, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: true, sortOrder: 1 },
        ],
      },
    },
  });
  fx = { tenantId: tenant.id, propertyId: property.id, unitId: unit.id, leaseId: lease.id };
  console.log(`Fixture: lease with Rent 10000 + Deposit(${depCt.nameEn}) 36000 first-invoice-only\n`);

  const base = await held2300(orgId);

  console.log('A. First invoice carries the deposit line');
  const inv1 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' }); // lease start month → first invoice
  createdInvoiceIds.push(inv1.id);
  await issueInvoice({ prisma, billing, approvals }, orgId, inv1.id);
  const inv1full = await prisma.invoice.findUniqueOrThrow({ where: { id: inv1.id }, include: { lines: { include: { chargeType: { select: { category: true } } } } } });
  const depLines = inv1full.lines.filter((l) => l.chargeType?.category === 'DEPOSIT');
  ck('A1 first invoice has a deposit charge line (36000)', depLines.length === 1 && depLines[0].amount.toString() === '36000');
  ck('A2 issuing credited Deposits Held by 36000', (await held2300(orgId)).minus(base).toFixed(2) === '36000.00');

  console.log('B. Paying it auto-creates a managed deposit — no double count');
  const total = inv1full.lines.reduce((s, l) => s.plus(l.amount.toString()), new Decimal(0)); // 46000
  const r1 = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: inv1.id, amount: total.toFixed(2) });
  createdReceiptIds.push(r1.id);
  await payments.approve({ organizationId: orgId, receiptId: r1.id });
  const auto = await prisma.deposit.findFirst({ where: { sourceInvoiceId: inv1.id } });
  autoDepositId = auto?.id ?? null;
  ck('B1 a Deposit row was auto-created from the invoice', !!auto);
  ck('B2 auto-deposit amount = 36000, HELD, linked', auto?.amount.toString() === '36000' && auto?.status === 'HELD' && auto?.leaseId === lease.id);
  ck('B3 Deposits Held is +36000 total (NOT doubled)', (await held2300(orgId)).minus(base).toFixed(2) === '36000.00', `got ${(await held2300(orgId)).minus(base).toFixed(2)}`);
  const sd = auto ? await deposits.settlementData(orgId, auto.id) : null;
  ck('B4 depositHeld reads 36000 via the invoice link', sd?.held === '36000.00', `got ${sd?.held}`);

  console.log('C. The auto-deposit behaves like a normal one (apply)');
  const inv2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02' });
  createdInvoiceIds.push(inv2.id);
  await issueInvoice({ prisma, billing, approvals }, orgId, inv2.id);
  if (auto) await deposits.apply({ organizationId: orgId, depositId: auto.id, invoiceId: inv2.id, amount: '10000' });
  const sd2 = auto ? await deposits.settlementData(orgId, auto.id) : null;
  ck('C1 after applying 10000, held = 26000', sd2?.held === '26000.00', `got ${sd2?.held}`);
  ck('C2 Deposits Held total now +26000 (36000 − 10000 applied)', (await held2300(orgId)).minus(base).toFixed(2) === '26000.00', `got ${(await held2300(orgId)).minus(base).toFixed(2)}`);
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    const invIds = createdInvoiceIds, depIds = autoDepositId ? [autoDepositId] : [];
    const src = [...invIds, ...createdReceiptIds, ...depIds];
    if (src.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: src } }, { 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 } } });
      }
    }
    if (createdReceiptIds.length) { await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: createdReceiptIds } } }); await prisma.receipt.deleteMany({ where: { id: { in: createdReceiptIds } } }); }
    if (depIds.length) { await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } }); await prisma.deposit.deleteMany({ where: { id: { in: depIds } } }); }
    if (invIds.length) await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    if (fx) { await prisma.lease.delete({ where: { id: fx.leaseId } }).catch(() => {}); await prisma.unit.deleteMany({ where: { id: fx.unitId } }); await prisma.property.delete({ where: { id: fx.propertyId } }).catch(() => {}); await prisma.tenant.delete({ where: { id: fx.tenantId } }).catch(() => {}); }
    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); });
