/**
 * Functional smoke: whole-lease charges apportioned by unit count on split DNs.
 * A lease over 5 units with ONE whole-lease rent rule of 50000: split-billing 3
 * units charges 30000 (50000 × 3/5); 1 unit charges 10000; whole lease 50000.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/split-apportion-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
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 { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
const created: string[] = [];
const rent = async (id: string) => (await prisma.invoiceLine.findMany({ where: { invoiceId: id, kind: 'CHARGE' } })).reduce((s, l) => s + Number(l.amount), 0);

async function purge() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-APP' } }, select: { id: true } });
  for (const l of leases) {
    const ids = (await prisma.invoice.findMany({ where: { leaseId: l.id }, select: { id: true } })).map((i) => i.id);
    if (ids.length) {
      const eids = (await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: ids } }, { lines: { some: { invoiceId: { in: ids } } } }] }, select: { id: true } })).map((e) => e.id);
      if (eids.length) { await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } }); await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } }); }
      await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
    }
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  const props = await prisma.property.findMany({ where: { name: 'ZZ Apportion Property' }, select: { id: true, units: { select: { id: true } } } });
  for (const pr of props) { await prisma.unit.deleteMany({ where: { id: { in: pr.units.map((u) => u.id) } } }); await prisma.property.delete({ where: { id: pr.id } }).catch(() => {}); }
  await prisma.tenant.deleteMany({ where: { name: 'ZZ Apportion Tenant' } });
}

async function main() {
  await purge();
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('no org');
  const orgId = org.id;
  const rentCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'RECURRING', glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!rentCt) throw new Error('no rent charge type');

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Apportion Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Apportion Property', units: { create: [{ name: 'ZA' }, { name: 'ZB' }, { name: 'ZC' }, { name: 'ZD' }, { name: 'ZE' }] } }, include: { units: true } });
  const u = property.units;
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-APP-${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: u.map((x) => ({ unitId: x.id })) },
      // One WHOLE-LEASE rent rule (no unitId) of 50000.
      chargeRules: { create: { chargeTypeId: rentCt.id, amount: '50000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', sortOrder: 0 } },
    },
  });
  console.log('Fixture: 5 units, ONE whole-lease rent rule = 50000\n');

  console.log('A. Split bill for 3 of 5 units → 50000 × 3/5');
  const inv3 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01', unitIds: [u[0].id, u[1].id, u[2].id] });
  created.push(inv3.id);
  ck('A1 three-unit split = 30000', (await rent(inv3.id)) === 30000, `got ${await rent(inv3.id)}`);

  console.log('B. Split bill for 1 of 5 units → 50000 × 1/5');
  const inv1 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02', unitIds: [u[3].id] });
  created.push(inv1.id);
  ck('B1 one-unit split = 10000', (await rent(inv1.id)) === 10000, `got ${await rent(inv1.id)}`);

  console.log('C. Whole-lease bill → full 50000');
  const invAll = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03' });
  created.push(invAll.id);
  ck('C1 whole lease = 50000', (await rent(invAll.id)) === 50000, `got ${await rent(invAll.id)}`);
}

async function cleanup() {
  try { await purge(); 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); });
