/**
 * Functional smoke for several debit notes on one lease in one month — rent on
 * one, utilities on another. Standalone, self-cleaning.
 *
 * The restriction that used to forbid this lived in generateDraft, and the
 * monthly bulk run relied on it entirely: with it gone and nothing put in its
 * place, every scheduled run would raise another full-rent note. So the case
 * that actually matters here is C — the run must be idempotent by its own
 * guard, not by an exception thrown somewhere else.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/multi-note-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: [] };

/** Non-VOID notes this lease carries for a period. */
async function notesFor(leaseId: string, period: string): Promise<number> {
  return prisma.invoice.count({ where: { leaseId, billingPeriod: period, status: { not: 'VOID' } } });
}

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, glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!rentCt) throw new Error('no charge type with a GL account');

  await purgeStale();

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Multi Tenant' } });
  created.tenantId = tenant.id;
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: 'ZZ Multi Property', units: { create: [{ name: 'ZZ M1' }, { name: 'ZZ M2' }] } },
    include: { units: true },
  });
  created.propertyId = property.id;
  const [unitA, unitB] = property.units;
  created.unitIds = [unitA.id, unitB.id];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-MULTI-${property.id.slice(-5)}`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: unitA.id }, { unitId: unitB.id }] },
      chargeRules: { create: { chargeTypeId: rentCt.id, amount: '10000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
    },
  });
  created.leaseId = lease.id;
  console.log('Fixture: one lease over two units, rent 10,000/month\n');

  const draft = async (period: string, unitIds?: string[]) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period, unitIds });
    created.invoiceIds.push(inv.id);
    return inv;
  };

  console.log('A. A second note for the same month is allowed');
  await draft('2020-01');
  let second: { id: string } | null = null;
  try {
    second = await draft('2020-01');
    ck('A1 the second note is created', true);
  } catch (e) {
    ck('A1 the second note is created', false, e instanceof Error ? e.message : String(e));
  }
  ck('A2 the lease carries two notes for 2020-01', (await notesFor(lease.id, '2020-01')) === 2, `got ${await notesFor(lease.id, '2020-01')}`);
  if (second) {
    const lines = await prisma.invoiceLine.findMany({ where: { invoiceId: second.id }, select: { amount: true } });
    // Honest about what "just lift the restriction" means: the rule-derived
    // charges are expanded again, so a second note is a blank cheque unless the
    // user removes what they do not want with an adjustment.
    ck('A3 rule-derived charges are expanded again on it', lines.some((l) => l.amount.toString() === '10000'), `got ${lines.map((l) => l.amount.toString())}`);
  }

  console.log('\nB. Split notes for the same units are allowed too');
  await draft('2020-02', [unitA.id]);
  try {
    await draft('2020-02', [unitA.id]);
    ck('B1 a second split note over the same unit is created', true);
  } catch (e) {
    ck('B1 a second split note over the same unit is created', false, e instanceof Error ? e.message : String(e));
  }

  console.log('\nC. The monthly run stays idempotent — the case the old guard was carrying');
  const first = await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-03' });
  for (const inv of await prisma.invoice.findMany({ where: { leaseId: lease.id, billingPeriod: '2020-03' }, select: { id: true } })) created.invoiceIds.push(inv.id);
  ck('C1 the first run raises one note', (await notesFor(lease.id, '2020-03')) === 1, `got ${await notesFor(lease.id, '2020-03')}`);
  ck('C2 it counted as created', first.created >= 1);
  const again = await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-03' });
  for (const inv of await prisma.invoice.findMany({ where: { leaseId: lease.id, billingPeriod: '2020-03' }, select: { id: true } })) created.invoiceIds.push(inv.id);
  ck('C3 running it again raises nothing', (await notesFor(lease.id, '2020-03')) === 1, `got ${await notesFor(lease.id, '2020-03')}`);
  ck('C4 the second run reports it as skipped, not created', again.skipped >= 1);

  const mine = await prisma.invoice.findFirstOrThrow({ where: { leaseId: lease.id, billingPeriod: '2020-03' }, select: { id: true } });
  await billing.voidInvoice({ organizationId: orgId, invoiceId: mine.id });
  const afterVoid = await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-03' });
  for (const inv of await prisma.invoice.findMany({ where: { leaseId: lease.id, billingPeriod: '2020-03' }, select: { id: true } })) created.invoiceIds.push(inv.id);
  ck('C5 a voided note does not block the run', (await notesFor(lease.id, '2020-03')) === 1 && afterVoid.created >= 1, `got ${await notesFor(lease.id, '2020-03')}`);

  const manual = await draft('2020-04');
  const runAfterManual = await billing.generateDraftsForPeriod({ organizationId: orgId, period: '2020-04' });
  for (const inv of await prisma.invoice.findMany({ where: { leaseId: lease.id, billingPeriod: '2020-04' }, select: { id: true } })) created.invoiceIds.push(inv.id);
  ck('C6 a hand-made note stops the run adding another', (await notesFor(lease.id, '2020-04')) === 1 && runAfterManual.created === 0, `got ${await notesFor(lease.id, '2020-04')} notes, created ${runAfterManual.created}`);
  void manual;
}

async function purgeStale() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-MULTI' } }, 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);
    await removeInvoices(ids);
    await prisma.leaseUnit.deleteMany({ where: { leaseId: l.id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: l.id } });
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  const props = await prisma.property.findMany({ where: { name: 'ZZ Multi Property' }, select: { id: true, units: { select: { id: true } } } });
  for (const p of props) {
    await prisma.unit.deleteMany({ where: { id: { in: p.units.map((u) => u.id) } } });
    await prisma.property.delete({ where: { id: p.id } }).catch(() => {});
  }
  await prisma.tenant.deleteMany({ where: { name: 'ZZ Multi Tenant' } });
}

async function removeInvoices(ids: string[]) {
  if (!ids.length) return;
  const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: ids } }, { lines: { some: { invoiceId: { in: ids } } } }] }, select: { id: true, reversesId: true } });
  const eids = entries.map((e) => e.id);
  if (eids.length) {
    await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
    const reversers = entries.filter((e) => e.reversesId).map((e) => e.id);
    if (reversers.length) await prisma.journalEntry.deleteMany({ where: { id: { in: reversers } } });
    await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
  }
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: ids } } });
  await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
}

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