/**
 * Functional smoke for draft adjustments + waive-interest. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/adjust-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 fx: { invoiceId?: string; leaseId?: string; propertyId?: string; unitId?: string; tenantId?: string } = {};

const total = async (id: string) => (await prisma.invoiceLine.findMany({ where: { invoiceId: id } })).reduce((s, l) => s + Number(l.amount), 0);

async function main() {
  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 Adj Tenant' } });
  fx.tenantId = tenant.id;
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Adj Property', units: { create: { name: 'ZZ AU1' } } }, include: { units: true } });
  fx.propertyId = property.id; fx.unitId = property.units[0].id;
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-ADJ-${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: property.units[0].id } },
      chargeRules: { create: { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
    },
  });
  fx.leaseId = lease.id;
  const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  fx.invoiceId = inv.id;
  console.log('Fixture: draft with rent 10000\n');

  console.log('A. Waiver (credit) reduces the total');
  ck('A0 draft total 10000', (await total(inv.id)) === 10000);
  await billing.addAdjustment({ organizationId: orgId, invoiceId: inv.id, chargeTypeId: rentCt.id, description: 'Goodwill discount', amount: '1000', credit: true });
  const waiver = (await prisma.invoiceLine.findMany({ where: { invoiceId: inv.id } })).find((l) => l.kind === 'WAIVER');
  ck('A1 waiver line is negative', !!waiver && Number(waiver.amount) === -1000, `got ${waiver?.amount}`);
  ck('A2 total now 9000', (await total(inv.id)) === 9000);

  console.log('B. One-off charge (positive) adds');
  await billing.addAdjustment({ organizationId: orgId, invoiceId: inv.id, chargeTypeId: rentCt.id, description: 'Key replacement', amount: '500', credit: false });
  ck('B1 total now 9500', (await total(inv.id)) === 9500);

  console.log('C. Remove the waiver adjustment');
  if (waiver) await billing.removeLine({ organizationId: orgId, lineId: waiver.id });
  ck('C1 total back to 10500 (rent 10000 + charge 500)', (await total(inv.id)) === 10500);

  console.log('D. A draft is a working document — the rent line comes off too');
  const rentLine = (await prisma.invoiceLine.findMany({ where: { invoiceId: inv.id } })).find((l) => l.kind === 'CHARGE' && !((l.meta as { adjustment?: boolean })?.adjustment));
  if (rentLine) await billing.removeLine({ organizationId: orgId, lineId: rentLine.id });
  ck('D1 the rule-derived rent line is removed', (await total(inv.id)) === 500, `got ${await total(inv.id)}`);

  console.log('D2. A line whose money has already moved is refused');
  const carried = await prisma.invoiceLine.create({ data: { invoiceId: inv.id, kind: 'OVERDUE_CARRYFORWARD', chargeTypeId: rentCt.id, description: 'Balance b/f', amount: '1000', sortOrder: -100 } });
  let blocked = false;
  try { await billing.removeLine({ organizationId: orgId, lineId: carried.id }); } catch { blocked = true; }
  ck('D2 a carried-forward balance cannot be removed', blocked);
  await prisma.invoiceLine.delete({ where: { id: carried.id } });

  console.log('E. Waive interest removes INTEREST lines');
  await prisma.invoiceLine.create({ data: { invoiceId: inv.id, kind: 'INTEREST', chargeTypeId: rentCt.id, description: 'Late interest', amount: '300', sortOrder: 999 } });
  ck('E0 interest line present', (await prisma.invoiceLine.count({ where: { invoiceId: inv.id, kind: 'INTEREST' } })) === 1);
  const res = await billing.waiveInterest({ organizationId: orgId, invoiceId: inv.id });
  ck('E1 one interest line removed', res.removed === 1);
  ck('E2 no interest line remains', (await prisma.invoiceLine.count({ where: { invoiceId: inv.id, kind: 'INTEREST' } })) === 0);
}

async function cleanup() {
  try {
    if (fx.invoiceId) await prisma.invoice.deleteMany({ where: { id: fx.invoiceId } }); // cascades lines
    if (fx.leaseId) await prisma.lease.delete({ where: { id: fx.leaseId } }).catch(() => {});
    if (fx.unitId) await prisma.unit.deleteMany({ where: { id: fx.unitId } });
    if (fx.propertyId) await prisma.property.delete({ where: { id: fx.propertyId } }).catch(() => {});
    if (fx.tenantId) 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); });
