/**
 * Functional smoke test for per-lease multi-currency. Standalone (writes to the
 * dev DB, self-cleans). Creates one HKD and one SGD lease under a single tenant,
 * issues an invoice in each, and proves the two currencies' books stay separate
 * and each balances — plus the cross-currency guards fire.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/currency-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 { ReportsService } from '../src/reports/reports.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 = 'ZZCUR';

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 reports = new ReportsService(prisma);

let pass = 0, fail = 0;
function check(name: string, cond: boolean, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}`); } else { fail++; console.log(`  ✗ ${name}   ${detail}`); }
}
async function expectThrow(name: string, fn: () => Promise<unknown>, contains: string) {
  try { await fn(); check(name, false, '(expected a throw)'); }
  catch (e) { const m = e instanceof Error ? e.message : String(e); check(name, m.includes(contains), `wrong message: "${m}"`); }
}

const createdInvoiceIds: string[] = [];
const createdReceiptIds: string[] = [];
const createdDepositIds: string[] = [];
let fx: { tenantId: string; propertyId: string; unitIds: string[]; leaseIds: string[] } | null = null;
// The reports use Hong Kong day boundaries, so "today" has to be the Hong
// Kong date. A UTC date is a day behind between midnight and 08:00 HKT, and
// every entry posted in those hours falls outside the window it asks for.
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('No organization seeded.');
  const orgId = org.id;
  const chargeType = await prisma.chargeType.findFirst({ where: { organizationId: orgId, glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!chargeType) throw new Error('No charge type with a GL account.');

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Cur Tenant' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Cur Property', units: { create: [{ name: 'ZZ U1' }, { name: 'ZZ U2' }] } },
    include: { units: true },
  });
  const mkLease = (unitId: string, currency: 'HKD' | 'SGD', rent: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-CUR-${currency}-${property.id.slice(-5)}`,
        tenantId: tenant.id, status: 'ACTIVE', currency,
        startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: { unitId } },
        chargeRules: { create: { chargeTypeId: chargeType.id, amount: rent, frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
      },
    });
  const leaseHKD = await mkLease(property.units[0].id, 'HKD', '10000');
  const leaseSGD = await mkLease(property.units[1].id, 'SGD', '5000');
  fx = { tenantId: tenant.id, propertyId: property.id, unitIds: property.units.map((u) => u.id), leaseIds: [leaseHKD.id, leaseSGD.id] };
  console.log(`Fixture: HKD lease (rent 10000) + SGD lease (rent 5000), one tenant\n`);

  const issue = async (leaseId: string, period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId, period });
    createdInvoiceIds.push(inv.id);
    await issueInvoice({ prisma, billing, approvals }, orgId, inv.id);
    return inv.id;
  };

  console.log('A. Issue an invoice in each currency');
  const invHKD = await issue(leaseHKD.id, '2099-01');
  const invSGD = await issue(leaseSGD.id, '2099-01');
  const hkd = await prisma.invoice.findUniqueOrThrow({ where: { id: invHKD }, select: { currency: true } });
  const sgd = await prisma.invoice.findUniqueOrThrow({ where: { id: invSGD }, select: { currency: true } });
  check('A1 HKD invoice tagged HKD', hkd.currency === 'HKD');
  check('A2 SGD invoice tagged SGD', sgd.currency === 'SGD');
  const eHKD = await prisma.journalEntry.findFirst({ where: { sourceType: 'INVOICE', sourceId: invHKD }, select: { currency: true, lines: { select: { currency: true } } } });
  check('A3 HKD invoice journal entry + lines are HKD', eHKD?.currency === 'HKD' && (eHKD?.lines ?? []).every((l) => l.currency === 'HKD'));
  const eSGD = await prisma.journalEntry.findFirst({ where: { sourceType: 'INVOICE', sourceId: invSGD }, select: { currency: true, lines: { select: { currency: true } } } });
  check('A4 SGD invoice journal entry + lines are SGD', eSGD?.currency === 'SGD' && (eSGD?.lines ?? []).every((l) => l.currency === 'SGD'));

  console.log('B. Trial balance keeps currencies separate, each balanced');
  const tb = await reports.trialBalance(orgId, today);
  const gHKD = tb.groups.find((g) => g.currency === 'HKD');
  const gSGD = tb.groups.find((g) => g.currency === 'SGD');
  check('B1 trial balance has both HKD and SGD groups', Boolean(gHKD && gSGD));
  check('B2 HKD group balances (DR==CR)', gHKD?.balanced === true, `DR ${gHKD?.totalDebit} CR ${gHKD?.totalCredit}`);
  check('B3 SGD group balances (DR==CR)', gSGD?.balanced === true, `DR ${gSGD?.totalDebit} CR ${gSGD?.totalCredit}`);
  const arCode = (await prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, role: 'RECEIVABLE' } })).code;
  const arHKD = gHKD?.rows.find((r) => r.code === arCode);
  const arSGD = gSGD?.rows.find((r) => r.code === arCode);
  // The HKD AR includes this test's 10000 plus any pre-existing demo HKD AR; assert SGD AR is exactly our 5000 (no demo SGD) and the two are distinct groups.
  check('B4 SGD receivable is exactly 5000 (separate from HKD)', arSGD?.debit === '5000.00', `got ${arSGD?.debit}`);
  check('B5 HKD receivable includes our 10000', new Decimal(arHKD?.debit ?? '0').gte(10000), `got ${arHKD?.debit}`);

  console.log('C. Cross-currency guards');
  await expectThrow('C1 one receipt cannot mix currencies', () =>
    payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '15000', allocations: [{ invoiceId: invHKD, amount: '10000' }, { invoiceId: invSGD, amount: '5000' }] }),
    'same currency');
  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: leaseSGD.id, amount: '5000' });
  createdDepositIds.push(dep.id);
  check('C2 deposit inherits its lease currency (SGD)', dep.currency === 'SGD');
  await expectThrow('C3 SGD deposit cannot be applied to an HKD invoice', () =>
    deposits.apply({ organizationId: orgId, depositId: dep.id, invoiceId: invHKD, amount: '1000' }), 'different currencies');

  console.log('D. Receipt inherits invoice currency');
  const rcpt = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: invSGD, amount: '5000' });
  createdReceiptIds.push(rcpt.id);
  check('D1 receipt for the SGD invoice is SGD', rcpt.currency === 'SGD');
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    const ids = createdInvoiceIds;
    const allSrc = [...ids, ...createdReceiptIds, ...createdDepositIds];
    if (allSrc.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: allSrc } }, { 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 (createdReceiptIds.length) { await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: createdReceiptIds } } }); await prisma.receipt.deleteMany({ where: { id: { in: createdReceiptIds } } }); }
    if (createdDepositIds.length) { await prisma.depositAllocation.deleteMany({ where: { depositId: { in: createdDepositIds } } }); await prisma.deposit.deleteMany({ where: { id: { in: createdDepositIds } } }); }
    if (createdInvoiceIds.length) await prisma.invoice.deleteMany({ where: { id: { in: createdInvoiceIds } } });
    if (fx) {
      for (const id of fx.leaseIds) await prisma.lease.delete({ where: { id } }).catch(() => {});
      await prisma.unit.deleteMany({ where: { id: { in: fx.unitIds } } });
      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); });
