/**
 * Functional smoke test for invoice VOID + the archive/CRUD ledger guards.
 * Standalone (NOT a *.test.ts, so `npm test`/CI never runs it — it writes to the
 * dev DB). It wires the real services by hand, creates an isolated long-term test
 * lease under the demo org, exercises every void path end-to-end, asserts the
 * ledger state, and deletes everything it created in a finally.
 *
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/void-smoke.ts
 */
import 'reflect-metadata';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } from '@rms/domain';
import { invoiceArState } from '../src/billing/invoice-ar';
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 { PrismaService } from '../src/prisma/prisma.service';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

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

let pass = 0;
let 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, but it succeeded)');
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    check(name, msg.includes(contains), `wrong message: "${msg}"`);
  }
}

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

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('No organization seeded — run the seed first.');
  const orgId = org.id;

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

  // Isolated fixture: a long-term ACTIVE lease so any 2099 period stays in-term.
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Smoke Tenant' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Smoke Property', units: { create: { name: 'ZZ Unit' } } },
    include: { units: true },
  });
  const unit = property.units[0];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId,
      reference: `ZZ-SMOKE-${property.id.slice(-6)}`,
      tenantId: tenant.id,
      status: 'ACTIVE',
      startDate: new Date('2020-01-01'),
      endDate: new Date('2100-01-01'),
      depositMonths: 0,
      units: { create: { unitId: unit.id } },
      chargeRules: {
        create: {
          chargeTypeId: chargeType.id,
          amount: '10000',
          frequencyMonths: 1,
          timing: 'ADVANCE',
          proration: 'FULL_MONTH',
          firstInvoiceOnly: false,
          sortOrder: 0,
        },
      },
    },
  });
  fixture = { leaseId: lease.id, tenantId: tenant.id, propertyId: property.id, unitId: unit.id };
  console.log(`Fixture: lease ${lease.reference} (${chargeType.nameEn} 10000/mo), tenant ${tenant.id.slice(-6)}\n`);

  const tx = prisma; // services open their own transactions; pass the base client to invoiceArState reads
  const gen = async (period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period });
    createdInvoiceIds.push(inv.id);
    return inv;
  };

  // ── A. Happy path: void a clean ISSUED invoice reverses the ledger ─────────
  console.log('A. Void a clean ISSUED invoice');
  {
    const draft = await gen('2099-01');
    await issueInvoice({ prisma, billing, approvals }, orgId, draft.id);
    const before = await invoiceArState(tx as never, orgId, draft.id);
    check('A1 issue posts AR (outstanding == chargeTotal > 0)', before.outstanding.gt(0) && before.outstanding.equals(before.chargeTotal));
    const voided = await billing.voidInvoice({ organizationId: orgId, invoiceId: draft.id });
    check('A2 void returns status VOID', voided.status === 'VOID');
    const after = await invoiceArState(tx as never, orgId, draft.id);
    check('A3 AR nets to 0 after void (issue reversed)', after.outstanding.isZero(), `outstanding=${after.outstanding.toFixed(2)}`);
    const issueEntry = await prisma.journalEntry.findFirst({ where: { organizationId: orgId, sourceType: 'INVOICE', sourceId: draft.id } });
    const reversal = issueEntry ? await prisma.journalEntry.findFirst({ where: { reversesId: issueEntry.id } }) : null;
    check('A4 a REVERSAL entry mirrors the issue posting', Boolean(reversal));
  }

  // ── B. A PENDING receipt blocks void ──────────────────────────────────────
  console.log('B. Pending receipt blocks void');
  {
    const draft = await gen('2099-02');
    await issueInvoice({ prisma, billing, approvals }, orgId, draft.id);
    const { outstanding } = await invoiceArState(tx as never, orgId, draft.id);
    const receipt = await payments.submitReceipt({ organizationId: orgId, tenantId: lease.tenantId, invoiceId: draft.id, amount: outstanding.toFixed(2) });
    createdReceiptIds.push(receipt.id);
    await expectThrow('B1 void refused while a receipt is pending', () => billing.voidInvoice({ organizationId: orgId, invoiceId: draft.id }), 'pending receipt');
    const reloaded = await prisma.invoice.findUniqueOrThrow({ where: { id: draft.id }, select: { status: true } });
    check('B2 invoice still ISSUED', reloaded.status === 'ISSUED');
  }

  // ── C. A carry-forward TARGET draft (has AR) cannot be voided as ledger-free ─
  console.log('C. Carry-forward target draft blocks void');
  {
    const src = await gen('2099-03');
    await issueInvoice({ prisma, billing, approvals }, orgId, src.id);
    const target = await billing.carryForward({ organizationId: orgId, invoiceId: src.id, targetPeriod: '2099-04' });
    createdInvoiceIds.push(target.id);
    check('C1 carry-forward creates a DRAFT target with a b/f line', target.status === 'DRAFT' && target.lines.some((l) => l.kind === 'OVERDUE_CARRYFORWARD'));
    await expectThrow('C2 void refused on a carry-forward target draft', () => billing.voidInvoice({ organizationId: orgId, invoiceId: target.id }), 'carries a balance');
    const reloaded = await prisma.invoice.findUniqueOrThrow({ where: { id: target.id }, select: { status: true } });
    check('C3 target still DRAFT (not stranded as VOID)', reloaded.status === 'DRAFT');
  }

  // ── D. A PAID invoice cannot be voided ────────────────────────────────────
  console.log('D. Paid invoice blocks void');
  {
    const draft = await gen('2099-05');
    await issueInvoice({ prisma, billing, approvals }, orgId, draft.id);
    const { outstanding } = await invoiceArState(tx as never, orgId, draft.id);
    const receipt = await payments.submitReceipt({ organizationId: orgId, tenantId: lease.tenantId, invoiceId: draft.id, amount: outstanding.toFixed(2) });
    createdReceiptIds.push(receipt.id);
    await payments.approve({ organizationId: orgId, receiptId: receipt.id });
    const reloaded = await prisma.invoice.findUniqueOrThrow({ where: { id: draft.id }, select: { status: true } });
    check('D1 invoice is PAID after approving full receipt', reloaded.status === 'PAID');
    await expectThrow('D2 void refused on a PAID invoice', () => billing.voidInvoice({ organizationId: orgId, invoiceId: draft.id }), 'fully-unpaid');
  }

  // ── E. approve refuses to post against a (raced) VOID invoice ──────────────
  console.log('E. Approve refuses a voided invoice (defense-in-depth)');
  {
    const draft = await gen('2099-06');
    await issueInvoice({ prisma, billing, approvals }, orgId, draft.id);
    const { outstanding } = await invoiceArState(tx as never, orgId, draft.id);
    const receipt = await payments.submitReceipt({ organizationId: orgId, tenantId: lease.tenantId, invoiceId: draft.id, amount: outstanding.toFixed(2) });
    createdReceiptIds.push(receipt.id);
    // Simulate the race: the invoice gets voided between submit and approve.
    await prisma.invoice.update({ where: { id: draft.id }, data: { status: 'VOID' } });
    await expectThrow('E1 approve refuses posting to a VOID invoice', () => payments.approve({ organizationId: orgId, receiptId: receipt.id }), 'voided');
  }

  // ── F. A plain DRAFT (no ledger) voids cleanly ────────────────────────────
  console.log('F. Void a plain DRAFT');
  {
    const draft = await gen('2099-07');
    const voided = await billing.voidInvoice({ organizationId: orgId, invoiceId: draft.id });
    check('F1 draft voids to VOID', voided.status === 'VOID');
    const lines = await prisma.journalLine.count({ where: { invoiceId: draft.id } });
    check('F2 no ledger lines were created for the draft', lines === 0);
  }

  // ── Global: the org ledger is still balanced (Σ DR == Σ CR) ────────────────
  console.log('G. Ledger integrity');
  {
    const lines = await prisma.journalLine.findMany({ where: { entry: { organizationId: orgId } }, select: { direction: true, amount: true } });
    let dr = new Decimal(0), cr = new Decimal(0);
    for (const l of lines) (l.direction === 'DEBIT' ? (dr = dr.plus(l.amount.toString())) : (cr = cr.plus(l.amount.toString())));
    check('G1 whole-org trial balance is balanced (DR == CR)', dr.equals(cr), `DR ${dr.toFixed(2)} vs CR ${cr.toFixed(2)}`);
  }
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    const ids = createdInvoiceIds;
    if (ids.length || createdReceiptIds.length) {
      const entries = await prisma.journalEntry.findMany({
        where: { OR: [{ sourceId: { in: [...ids, ...createdReceiptIds] } }, { lines: { some: { invoiceId: { in: ids } } } }] },
        select: { id: true, reversesId: true },
      });
      const entryIds = entries.map((e) => e.id);
      if (entryIds.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: entryIds } } });
        // Delete REVERSAL entries before the originals they point at (reversesId is Restrict).
        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: entryIds } } });
      }
      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 (fixture) {
      await prisma.lease.delete({ where: { id: fixture.leaseId } }); // cascades chargeRules + leaseUnits
      await prisma.unit.delete({ where: { id: fixture.unitId } });
      await prisma.property.delete({ where: { id: fixture.propertyId } });
      await prisma.tenant.delete({ where: { id: fixture.tenantId } });
    }
    console.log('\nCleanup: OK (all test records removed)');
  } 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);
  });
