/**
 * Smoke for early lease termination: the date is recorded, the final part-month
 * debit note is prorated to it, the deposit surfaces for settlement, and
 * settling that deposit no longer touches the lease.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/terminate-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 { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { NumberService } from '../src/common/number.service';
import { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const ledger = new LedgerService();
const numbers = new NumberService();
const billing = new BillingService(prisma, ledger, numbers, new EventEmitter2(), approvals);
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 throws = async (n: string, fn: () => Promise<unknown>, needle: string) => {
  try { await fn(); ck(n, false, 'did not throw'); }
  catch (e) { const m = e instanceof Error ? e.message : String(e); ck(n, m.includes(needle), `got "${m}"`); }
};

const PFX = 'ZZ-TRM';
const ORG_CODE = `${PFX}-ORG`;

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: PFX } }, select: { id: true } });
  const leaseIds = leases.map((l) => l.id);
  if (leaseIds.length) {
    const invs = await prisma.invoice.findMany({ where: { leaseId: { in: leaseIds } }, select: { id: true } });
    const depRows = await prisma.deposit.findMany({ where: { leaseId: { in: leaseIds } }, select: { id: true } });
    const ids = [...invs.map((i) => i.id), ...depRows.map((d) => d.id), ...leaseIds];
    await prisma.journalLine.deleteMany({ where: { OR: [{ invoiceId: { in: invs.map((i) => i.id) } }, { entry: { sourceId: { in: ids } } }] } });
    await prisma.journalEntry.deleteMany({ where: { sourceId: { in: ids } } });
    await prisma.depositSettlementLine.deleteMany({ where: { settlement: { depositId: { in: depRows.map((d) => d.id) } } } });
    await prisma.depositSettlement.deleteMany({ where: { depositId: { in: depRows.map((d) => d.id) } } });
    await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depRows.map((d) => d.id) } } });
    await prisma.deposit.deleteMany({ where: { id: { in: depRows.map((d) => d.id) } } });
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invs.map((i) => i.id) } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invs.map((i) => i.id) } } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.lease.updateMany({ where: { id: { in: leaseIds } }, data: { renewedFromId: null } });
    await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  }
  if (org) {
    const props = await prisma.property.findMany({ where: { organizationId: org.id }, select: { id: true } });
    await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
    await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
    await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
    await prisma.journalLine.deleteMany({ where: { entry: { organizationId: org.id } } });
    await prisma.journalEntry.deleteMany({ where: { organizationId: org.id } });
    await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
    await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
    await prisma.numberSequence.deleteMany({ where: { organizationId: org.id } });
    await prisma.organization.delete({ where: { id: org.id } });
  }
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Termination smoke org' } })).id;

  // Minimum chart of accounts the billing + deposit postings need.
  const glDefs = [
    { code: '1100', name: 'AR', type: 'ASSET' as const, role: 'RECEIVABLE' as const },
    { code: '1000', name: 'Bank', type: 'ASSET' as const, role: 'BANK' as const },
    { code: '4000', name: 'Rental Income', type: 'INCOME' as const },
    { code: '2300', name: 'Deposits Held', type: 'LIABILITY' as const, role: 'DEPOSITS_HELD' as const },
    { code: '2310', name: 'Refunds Payable', type: 'LIABILITY' as const, role: 'REFUNDS_PAYABLE' as const },
  ];
  const gl: Record<string, string> = {};
  for (const g of glDefs) gl[g.code] = (await prisma.glAccount.create({ data: { organizationId: orgId, ...g } })).id;
  const rent = await prisma.chargeType.create({
    data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: gl['4000'] },
  });
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'DN-', padding: 6 } });
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'DEPOSIT', prefix: 'DEP-', padding: 6 } });

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant` } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, name: `${PFX} Property`, units: { create: { name: `${PFX} U1` } } } });
  const unit = await prisma.unit.findFirstOrThrow({ where: { propertyId: prop.id } });

  const mkLease = async (ref: string, start: string, end: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: ref, tenantId: tenant.id,
        status: 'ACTIVE', currency: 'HKD', startDate: new Date(start), endDate: new Date(end), depositMonths: 0,
        units: { create: { unitId: unit.id } },
        chargeRules: { create: [{ chargeTypeId: rent.id, amount: '31000.00', frequencyMonths: 1, timing: 'ADVANCE', proration: 'DAILY', sortOrder: 0 }] },
      },
    });

  const leaseOf = (id: string) => prisma.lease.findUniqueOrThrow({ where: { id } });

  // ── A: terminate mid-month → final note prorated to the day ──
  console.log('\nA. termination raises the prorated final note');
  const a = await mkLease(`${PFX}-A`, '2026-01-01', '2027-12-31');
  const res = await billing.terminateLease({ organizationId: orgId, leaseId: a.id, terminationDate: new Date('2026-08-10T00:00:00.000Z'), reason: 'tenant moving out' });
  const la = await leaseOf(a.id);
  ck('A1 status is TERMINATED', la.status === 'TERMINATED', la.status);
  ck('A2 terminatedAt recorded', la.terminatedAt?.toISOString().slice(0, 10) === '2026-08-10', String(la.terminatedAt));
  ck('A3 contracted endDate untouched', la.endDate.toISOString().slice(0, 10) === '2027-12-31', String(la.endDate));
  ck('A4 reason recorded', la.terminationReason === 'tenant moving out', String(la.terminationReason));
  ck('A5 a final draft note was raised', res.finalInvoiceId !== null && res.finalInvoiceSkipped === null, JSON.stringify(res));

  const finalInv = await prisma.invoice.findUniqueOrThrow({ where: { id: res.finalInvoiceId! }, include: { lines: true } });
  // Aug has 31 days; 1–10 inclusive = 10 days. 31000 × 10/31 = 10000.00 exactly.
  ck('A6 final note is a DRAFT for 2026-08', finalInv.status === 'DRAFT' && finalInv.billingPeriod === '2026-08', `${finalInv.status} ${finalInv.billingPeriod}`);
  ck('A7 rent prorated to 10/31 days = 10000.00', finalInv.lines[0]?.amount.toFixed(2) === '10000.00', `got ${finalInv.lines[0]?.amount.toFixed(2)}`);
  ck('A8 line describes the covered window', finalInv.lines[0]?.description.includes('2026-08-01 → 2026-08-10'), finalInv.lines[0]?.description);

  await throws('A9 terminating twice is refused', () =>
    billing.terminateLease({ organizationId: orgId, leaseId: a.id, terminationDate: new Date('2026-09-01T00:00:00.000Z') }), 'Only an active lease');

  // ── B: date validation ──
  console.log('\nB. termination date bounds');
  const b = await mkLease(`${PFX}-B`, '2026-03-01', '2026-12-31');
  await throws('B1 before the lease starts is refused', () =>
    billing.terminateLease({ organizationId: orgId, leaseId: b.id, terminationDate: new Date('2026-02-01T00:00:00.000Z') }), 'cannot be before');
  await throws('B2 after the contracted end is refused', () =>
    billing.terminateLease({ organizationId: orgId, leaseId: b.id, terminationDate: new Date('2027-01-05T00:00:00.000Z') }), 'contracted end');
  ck('B3 the lease is still ACTIVE after both refusals', (await leaseOf(b.id)).status === 'ACTIVE');

  // ── C: the month is already billed → no duplicate note ──
  console.log('\nC. a month that is already billed');
  const c = await mkLease(`${PFX}-C`, '2026-01-01', '2027-12-31');
  await billing.generateDraft({ organizationId: orgId, leaseId: c.id, period: '2026-08' });
  const cRes = await billing.terminateLease({ organizationId: orgId, leaseId: c.id, terminationDate: new Date('2026-08-20T00:00:00.000Z') });
  ck('C1 terminated anyway', (await leaseOf(c.id)).status === 'TERMINATED');
  ck('C2 no duplicate note, reported as ALREADY_BILLED', cRes.finalInvoiceId === null && cRes.finalInvoiceSkipped === 'ALREADY_BILLED', JSON.stringify(cRes));
  ck('C3 still exactly one note for 2026-08', (await prisma.invoice.count({ where: { leaseId: c.id, billingPeriod: '2026-08' } })) === 1);

  // ── D: a terminated lease cannot be billed past its termination date ──
  console.log('\nD. billing after the termination date');
  await throws('D1 a later period has nothing to charge', () =>
    billing.generateDraft({ organizationId: orgId, leaseId: a.id, period: '2026-09' }), 'No charges apply');

  // ── E: preflight surfaces the loose ends, deposit settlement leaves the lease alone ──
  console.log('\nE. deposit hand-off');
  const e = await mkLease(`${PFX}-E`, '2026-01-01', '2027-12-31');
  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: e.id, amount: '62000' });
  const held = await deposits.heldForLease(orgId, e.id);
  ck('E1 heldForLease reports the ledger balance', held.length === 1 && held[0].held === '62000.00', JSON.stringify(held));

  const openBefore = await billing.leaseOpenInvoices(orgId, e.id);
  ck('E2 no open notes yet', openBefore.length === 0, JSON.stringify(openBefore));

  await billing.terminateLease({ organizationId: orgId, leaseId: e.id, terminationDate: new Date('2026-08-10T00:00:00.000Z') });
  const openAfter = await billing.leaseOpenInvoices(orgId, e.id);
  ck('E3 the final draft shows up as an open note', openAfter.length === 1 && openAfter[0].status === 'DRAFT' && openAfter[0].outstanding === '10000.00', JSON.stringify(openAfter));

  const awaiting = await deposits.awaitingSettlement(orgId);
  const mine = awaiting.filter((x) => x.leaseRef?.startsWith(PFX));
  ck('E4 the deposit is awaiting settlement after termination', mine.some((x) => x.id === dep.id), JSON.stringify(mine.map((x) => x.leaseRef)));
  ck('E5 it reports the termination date, not the contracted end',
    mine.find((x) => x.id === dep.id)?.endDate?.toISOString().slice(0, 10) === '2026-08-10',
    String(mine.find((x) => x.id === dep.id)?.endDate));

  await deposits.settle({ organizationId: orgId, depositId: dep.id, settledByUserId: null });
  ck('E6 settling the deposit leaves the lease TERMINATED (not ENDED)', (await leaseOf(e.id)).status === 'TERMINATED', (await leaseOf(e.id)).status);

  // ── F: a lease whose term passed but the nightly job has not run ──
  console.log('\nF. expired but not yet flipped');
  const f = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${PFX}-F`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0,
    },
  });
  const depF = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: f.id, amount: '5000' });
  const awaitingF = await deposits.awaitingSettlement(orgId);
  ck('F1 its deposit is settleable without waiting for the nightly job', awaitingF.some((x) => x.id === depF.id));
}

main()
  .catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); })
  .finally(async () => {
    await purge().catch((e) => console.log('cleanup warn', e instanceof Error ? e.message : e));
    await prisma.$disconnect();
    console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} passed, ${fail} failed`);
    process.exit(fail === 0 ? 0 : 1);
  });
