/**
 * Functional smoke test for auto late-interest. Standalone (writes to the dev DB,
 * self-cleans). Proves: an overdue invoice's interest is computed per the policy's
 * rate basis and billed onto the NEXT debit note, and the same days are never
 * charged twice.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/interest-smoke.ts
 */
import 'reflect-metadata';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
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';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), approvals);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

const createdInvoiceIds: string[] = [];
let fx: { tenantId: string; propertyId: string; unitId: string; leaseId: string; policyId: string } | null = null;
const DAY = 86_400_000;

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

  await prisma.interestPolicy.deleteMany({ where: { organizationId: orgId, code: 'ZZTESTINT' } });
  const policy = await prisma.interestPolicy.create({
    data: { organizationId: orgId, code: 'ZZTESTINT', name: 'ZZ Test Interest', ratePercent: '0.100000', rateBasis: 'DAILY', graceDays: 0, isActive: true },
  });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Int Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Int Property', units: { create: { name: 'ZZ IU1' } } }, include: { units: true } });
  const unit = property.units[0];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-INT-${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,
      interestPolicyId: policy.id,
      units: { create: { unitId: unit.id } },
      chargeRules: { create: { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
    },
  });
  fx = { tenantId: tenant.id, propertyId: property.id, unitId: unit.id, leaseId: lease.id, policyId: policy.id };
  console.log('Fixture: lease @ 0.1%/day interest, rent 10000\n');

  console.log('A. Overdue invoice');
  const inv1 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  createdInvoiceIds.push(inv1.id);
  await issueInvoice({ prisma, billing, approvals }, orgId, inv1.id);
  // Force it 10 days overdue.
  const dueDate = new Date(Date.now() - 10 * DAY);
  await prisma.invoice.update({ where: { id: inv1.id }, data: { dueDate } });
  ck('A1 invoice issued, outstanding 10000', true);

  console.log('B. Interest lands on the NEXT debit note, per the daily basis');
  const inv2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02' });
  createdInvoiceIds.push(inv2.id);
  const inv2full = await prisma.invoice.findUniqueOrThrow({ where: { id: inv2.id }, include: { lines: true } });
  const intLine = inv2full.lines.find((l) => l.kind === 'INTEREST');
  // 10000 × (0.1/100/1) × 10 days = 100.00  (daily basis; monthly would be ~3.33)
  ck('B1 next draft has an INTEREST line', !!intLine);
  ck('B2 interest = 100.00 (10000 × 0.1%/day × 10d)', intLine?.amount.toString() === '100', `got ${intLine?.amount.toString()}`);
  const inv1after = await prisma.invoice.findUniqueOrThrow({ where: { id: inv1.id }, select: { interestAccruedTo: true } });
  ck('B3 source invoice marked accrued', inv1after.interestAccruedTo != null);

  console.log('C. No double-charge on a re-generated draft same day');
  const inv3 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03' });
  createdInvoiceIds.push(inv3.id);
  const inv3full = await prisma.invoice.findUniqueOrThrow({ where: { id: inv3.id }, include: { lines: true } });
  ck('C1 no interest re-charged (already accrued to now)', !inv3full.lines.some((l) => l.kind === 'INTEREST'));

  console.log('D. Issuing the interest bill posts to the late interest charge\'s account');
  const gl = await prisma.glAccount.findFirst({ where: { organizationId: orgId, chargeTypes: { some: { code: 'LATE_INTEREST' } } } });
  const before = gl ? await sumCredit(gl.id) : 0;
  await issueInvoice({ prisma, billing, approvals }, orgId, inv2.id);
  const after = gl ? await sumCredit(gl.id) : 0;
  ck('D1 that account credited by 100', (after - before).toFixed(2) === '100.00', `delta ${after - before}`);
}

async function sumCredit(accountId: string): Promise<number> {
  const lines = await prisma.journalLine.findMany({ where: { accountId }, select: { direction: true, amount: true } });
  return lines.reduce((s, l) => s + (l.direction === 'CREDIT' ? Number(l.amount) : -Number(l.amount)), 0);
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    if (createdInvoiceIds.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: createdInvoiceIds } }, { lines: { some: { invoiceId: { in: createdInvoiceIds } } } }] }, select: { id: true, reversesId: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        const rev = entries.filter((e) => e.reversesId).map((e) => e.id);
        if (rev.length) await prisma.journalEntry.deleteMany({ where: { id: { in: rev } } });
        await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
      }
      await prisma.invoice.deleteMany({ where: { id: { in: createdInvoiceIds } } });
    }
    if (fx) {
      await prisma.lease.delete({ where: { id: fx.leaseId } }).catch(() => {});
      await prisma.unit.deleteMany({ where: { id: fx.unitId } });
      await prisma.property.delete({ where: { id: fx.propertyId } }).catch(() => {});
      await prisma.tenant.delete({ where: { id: fx.tenantId } }).catch(() => {});
      await prisma.interestPolicy.delete({ where: { id: fx.policyId } }).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); });
