/**
 * Functional smoke test for the landing page's KPI tiles. Standalone (writes to
 * the dev DB, self-cleans). Proves the four figures come from the ledger and
 * hold the invariants the tiles depend on: the zero state is empty rather than
 * zeroed, currencies are never summed, a void note leaves no trace, a draft is
 * not "issued this month", and the outstanding total always equals the AR Aging
 * report's — the two must never disagree by construction.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/dashboard-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 { 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 = 'ZZDSH';

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

const createdInvoiceIds: string[] = [];
const createdReceiptIds: string[] = [];
let fx: { tenantId: string; propertyId: string; unitIds: string[]; leaseIds: string[] } | null = null;

/** The month the fixture's notes are issued into — the tiles read issueDate, and
 *  issue() stamps now(), so "this month" is genuinely today's month. */
// Hong Kong dates throughout: the reports use Hong Kong day boundaries, and a
// UTC date is a day behind between midnight and 08:00 HKT — every entry posted
// in those hours would fall outside the window the smoke asks for.
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });
const month = today.slice(0, 7);
/** A currency with nothing outstanding has no row at all — that IS zero, and
 *  the tile renders it as such, so assertions must read it the same way. */
const amountOf = (rows: { currency: string; amount: string }[], c: string) => rows.find((r) => r.currency === c)?.amount ?? '0.00';
const rateOf = (rows: { currency: string; rate: string }[], c: string) => rows.find((r) => r.currency === c)?.rate;

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

  console.log('Z. Baseline — whatever is already in this database');
  const base = await reports.dashboard(orgId, month);
  const baseHkdOut = new Decimal(amountOf(base.outstandingAr, 'HKD') ?? '0');
  const baseHkdInv = new Decimal(amountOf(base.invoicedThisMonth, 'HKD') ?? '0');
  const baseLeases = base.activeLeases;
  check('Z1 the month reported back is the one asked for', base.month === month, `got ${base.month}`);
  check('Z2 a currency with nothing charged gets no rate row (0/0 is not 0%)',
    base.collectionRate.every((r) => new Decimal(r.rate).gte(0)), JSON.stringify(base.collectionRate));
  console.log(`     baseline: leases=${baseLeases} HKD outstanding=${baseHkdOut} HKD invoiced=${baseHkdInv}\n`);

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Dash Tenant' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Dash Property', units: { create: [{ name: 'ZZ D1' }, { name: 'ZZ D2' }, { name: 'ZZ D3' }] } },
    include: { units: true },
  });
  const mkLease = (unitId: string, currency: 'HKD' | 'SGD', rent: string, endDate: Date, tag: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-DASH-${tag}-${property.id.slice(-5)}`,
        tenantId: tenant.id, status: 'ACTIVE', currency,
        startDate: new Date('2020-01-01'), endDate, depositMonths: 0,
        units: { create: { unitId } },
        chargeRules: { create: { chargeTypeId: chargeType.id, amount: rent, frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
      },
    });
  const live = await mkLease(property.units[0].id, 'HKD', '10000', new Date('2100-01-01'), 'LIVE');
  const sgd = await mkLease(property.units[1].id, 'SGD', '5000', new Date('2100-01-01'), 'SGD');
  // ACTIVE in the column, but its term ended — the tile must not count it.
  const expired = await mkLease(property.units[2].id, 'HKD', '9999', new Date('2020-06-30'), 'EXPD');
  fx = { tenantId: tenant.id, propertyId: property.id, unitIds: property.units.map((u) => u.id), leaseIds: [live.id, sgd.id, expired.id] };
  console.log('Fixture: HKD lease 10000, SGD lease 5000, plus one ACTIVE-but-expired HKD lease\n');

  console.log('L. Active lease count');
  const afterLeases = await reports.dashboard(orgId, month);
  check('L1 two live leases counted, the expired one is not', afterLeases.activeLeases === baseLeases + 2,
    `expected ${baseLeases + 2}, got ${afterLeases.activeLeases}`);

  console.log('\nI. Invoiced this month is face value of ISSUED notes, per currency');
  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;
  };
  const invHkd = await issue(live.id, '2099-01');
  const invSgd = await issue(sgd.id, '2099-02');
  const afterIssue = await reports.dashboard(orgId, month);
  check('I1 the HKD note adds its face value', amountOf(afterIssue.invoicedThisMonth, 'HKD') === baseHkdInv.plus(10000).toFixed(2),
    `got ${amountOf(afterIssue.invoicedThisMonth, 'HKD')}`);
  check('I2 the SGD note lands in its own currency row, not added to HKD', amountOf(afterIssue.invoicedThisMonth, 'SGD') === '5000.00',
    `got ${amountOf(afterIssue.invoicedThisMonth, 'SGD')}`);
  check('I3 billingPeriod is irrelevant — both notes are for 2099 but issued today',
    afterIssue.invoicedThisMonth.length >= 2);

  console.log('\nD. A draft is not yet invoiced');
  const draft = await billing.generateDraft({ organizationId: orgId, leaseId: live.id, period: '2099-03' });
  createdInvoiceIds.push(draft.id);
  const afterDraft = await reports.dashboard(orgId, month);
  check('D1 an unissued draft changes nothing', amountOf(afterDraft.invoicedThisMonth, 'HKD') === amountOf(afterIssue.invoicedThisMonth, 'HKD'));

  console.log('\nO. Outstanding, and its agreement with AR Aging');
  check('O1 the issued HKD note is outstanding in full', amountOf(afterDraft.outstandingAr, 'HKD') === baseHkdOut.plus(10000).toFixed(2),
    `got ${amountOf(afterDraft.outstandingAr, 'HKD')}`);
  check('O2 SGD outstanding is its own 5000', amountOf(afterDraft.outstandingAr, 'SGD') === '5000.00',
    `got ${amountOf(afterDraft.outstandingAr, 'SGD')}`);
  const aging = await reports.arAging(orgId, today);
  for (const cur of ['HKD', 'SGD'] as const) {
    const fromAging = aging.groups.find((g) => g.currency === cur)?.totals.total ?? '0.00';
    const fromTile = amountOf(afterDraft.outstandingAr, cur) ?? '0.00';
    check(`O3 ${cur} tile equals the AR Aging total`, fromAging === fromTile, `aging ${fromAging} vs tile ${fromTile}`);
  }

  console.log('\nC. Collection rate follows the ledger, both ways');
  const before = await reports.dashboard(orgId, month);
  const rcpt = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '5000', allocations: [{ invoiceId: invSgd, amount: '5000' }],
  });
  createdReceiptIds.push(rcpt.id);
  const afterPending = await reports.dashboard(orgId, month);
  check('C1 a PENDING receipt posts nothing, so nothing moves', amountOf(afterPending.outstandingAr, 'SGD') === amountOf(before.outstandingAr, 'SGD'),
    `got ${amountOf(afterPending.outstandingAr, 'SGD')}`);
  await payments.approve({ organizationId: orgId, receiptId: rcpt.id });
  const afterPaid = await reports.dashboard(orgId, month);
  check('C2 approving clears the SGD outstanding', amountOf(afterPaid.outstandingAr, 'SGD') === '0.00',
    `got ${JSON.stringify(afterPaid.outstandingAr)}`);
  check('C3 SGD is fully collected', rateOf(afterPaid.collectionRate, 'SGD') === '100.0', `got ${rateOf(afterPaid.collectionRate, 'SGD')}`);
  const hkdRate = rateOf(afterPaid.collectionRate, 'HKD');
  check('C4 HKD rate is a real percentage between 0 and 100', hkdRate !== undefined && new Decimal(hkdRate).gte(0) && new Decimal(hkdRate).lte(100), `got ${hkdRate}`);

  console.log('\nV. Voiding removes a note from both tiles');
  await billing.voidInvoice({ organizationId: orgId, invoiceId: invHkd });
  const afterVoid = await reports.dashboard(orgId, month);
  check('V1 a voided note is no longer invoiced this month', amountOf(afterVoid.invoicedThisMonth, 'HKD') === baseHkdInv.toFixed(2),
    `got ${amountOf(afterVoid.invoicedThisMonth, 'HKD')}`);
  check('V2 a voided note is no longer outstanding', amountOf(afterVoid.outstandingAr, 'HKD') === baseHkdOut.toFixed(2),
    `expected ${baseHkdOut.toFixed(2)}, got ${amountOf(afterVoid.outstandingAr, 'HKD')}`);
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    const ids = createdInvoiceIds;
    const allSrc = [...ids, ...createdReceiptIds];
    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 (ids.length) await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
    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); });
