/**
 * Functional smoke: per-unit rent on split debit notes. Standalone, self-cleaning.
 * A lease over flats A/B/C with per-unit rent (15k/10k/10k): a split bill for
 * A+B charges 25k (their actual rents), the whole-lease bill charges 35k.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/per-unit-rent-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: { invoiceIds: string[]; leaseId?: string; propertyId?: string; unitIds: string[]; tenantId?: string } = { invoiceIds: [], unitIds: [] };
const rentTotal = 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-PUR' } }, 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 PerUnit 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 PerUnit 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 PerUnit Tenant' } });
  created.tenantId = tenant.id;
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ PerUnit Property', units: { create: [{ name: 'ZZ A' }, { name: 'ZZ B' }, { name: 'ZZ C' }] } }, include: { units: true } });
  created.propertyId = property.id;
  const [A, B, C] = property.units;
  created.unitIds = [A.id, B.id, C.id];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-PUR-${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: [{ unitId: A.id }, { unitId: B.id }, { unitId: C.id }] },
      chargeRules: {
        create: [
          { chargeTypeId: rentCt.id, unitId: A.id, amount: '15000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', sortOrder: 0 },
          { chargeTypeId: rentCt.id, unitId: B.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', sortOrder: 1 },
          { chargeTypeId: rentCt.id, unitId: C.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', sortOrder: 2 },
        ],
      },
    },
  });
  created.leaseId = lease.id;
  console.log('Fixture: per-unit rent A=15000, B=10000, C=10000\n');

  console.log('A. Split bill for A+B charges only their rent');
  const invAB = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01', unitIds: [A.id, B.id] });
  created.invoiceIds.push(invAB.id);
  ck('A1 A+B split = 25000 (15000 + 10000)', (await rentTotal(invAB.id)) === 25000, `got ${await rentTotal(invAB.id)}`);

  console.log('B. Whole-lease bill charges all three');
  const invAll = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02' });
  created.invoiceIds.push(invAll.id);
  ck('B1 whole lease = 35000 (15000 + 10000 + 10000)', (await rentTotal(invAll.id)) === 35000, `got ${await rentTotal(invAll.id)}`);

  console.log('C. Split bill for C alone charges only C');
  const invC = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03', unitIds: [C.id] });
  created.invoiceIds.push(invC.id);
  ck('C1 C split = 10000', (await rentTotal(invC.id)) === 10000, `got ${await rentTotal(invC.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); });
