/**
 * Functional smoke for planned charges and for rebuilding a draft — the two
 * paths that had no coverage at all, and which interact badly.
 *
 * A planned charge is booked ahead for a month and must be billed EXACTLY once:
 * consumed by the note that bills it, released if that note is undone. The
 * dangerous combination is a rebuild of a SPLIT note, because that is the only
 * call where both `reclaimFor` and `scopeUnitIds` are set at once — and the
 * filter that keeps an already-billed charge off the note is built from the same
 * spread as the unit filter. D3/D4/D6 below are what a duplicate key there costs.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/planned-charge-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { StorageService } from '../src/attachments/storage.service';
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 { MaintenanceService } from '../src/maintenance/maintenance.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), approvals);
const maintenance = new MaintenanceService(prisma, new EventEmitter2(), new StorageService(new ConfigService()));
const deps = { prisma, billing, approvals };

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

const REF = 'ZZ-PLN';
const PROP = 'ZZ Planned Property';
const TENANT = 'ZZ Planned Tenant';
const SERIAL = 'ZZ-PLN-';
const CT_CODE = 'ZZPLNW';

const linesOf = (invoiceId: string) =>
  prisma.invoiceLine.findMany({ where: { invoiceId }, orderBy: { sortOrder: 'asc' }, select: { id: true, description: true, amount: true } });

const countLines = async (invoiceId: string, needle: string) =>
  (await linesOf(invoiceId)).filter((l) => l.description.includes(needle)).length;

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 purgeStale();

  const water = await prisma.chargeType.create({ data: { organizationId: orgId, code: CT_CODE, nameEn: 'ZZ Planned Water', category: 'UTILITY', isActive: true, sortOrder: 997 } });

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: PROP, units: { create: [{ name: 'ZZ Pln A' }, { name: 'ZZ Pln B' }] } },
    include: { units: true },
  });
  await prisma.utilityTariff.create({ data: { chargeTypeId: water.id, propertyId: property.id, unitRate: '10', fixedCharge: '0' } });
  const [unitA, unitB] = property.units;

  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-1`, 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 },
        { chargeTypeId: water.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 },
      ] },
    },
  });

  const plan = (period: string, description: string, amount: string, unitId: string | null = null) =>
    prisma.plannedCharge.create({ data: { organizationId: orgId, leaseId: lease.id, chargeTypeId: rentCt.id, period, description, amount, unitId } });

  const claimOf = async (id: string) => (await prisma.plannedCharge.findUniqueOrThrow({ where: { id }, select: { billedInvoiceId: true } })).billedInvoiceId;

  console.log('A. A booked charge lands on that month, exactly once');
  const p1 = await plan('2020-01', 'ZZ Aircon repair', '5000');
  const inv1 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  ck('A1 it is on the note for its month', (await countLines(inv1.id, 'ZZ Aircon repair')) === 1);
  ck('A2 and is stamped as billed by it', (await claimOf(p1.id)) === inv1.id);
  const inv1b = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  ck('A3 a second note that month does not repeat it', (await countLines(inv1b.id, 'ZZ Aircon repair')) === 0);
  // Booked ahead and still unclaimed, so ONLY the period filter can keep it off
  // this month's note — A4 would otherwise pass on the already-billed arm alone.
  const future = await plan('2020-09', 'ZZ Future topup', '900');
  const other = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-02' });
  ck('A4 a note for another month never had it', (await countLines(other.id, 'ZZ Aircon repair')) === 0);
  ck('A5 a charge booked for a future month is not swept in early', (await countLines(other.id, 'ZZ Future topup')) === 0);
  ck('A6 and it is left unclaimed, waiting for its own month', (await claimOf(future.id)) === null);

  console.log('\nB. Undoing the note that billed it puts it back in the queue');
  await billing.voidInvoice({ organizationId: orgId, invoiceId: inv1.id });
  ck('B1 voiding releases it', (await claimOf(p1.id)) === null);
  const inv2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  ck('B2 the next note for that month picks it up again', (await countLines(inv2.id, 'ZZ Aircon repair')) === 1);

  console.log('\nC. Rebuilding a WHOLE-LEASE note keeps its own charge once');
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: inv2.id });
  ck('C1 still exactly one line after a rebuild', (await countLines(inv2.id, 'ZZ Aircon repair')) === 1);
  ck('C2 and it still belongs to this note', (await claimOf(p1.id)) === inv2.id);

  console.log('\nD. Rebuilding a SPLIT note must not steal another note’s charge');
  const p2 = await plan('2020-03', 'ZZ Repaint', '7000');
  // A whole-lease planned charge, so the first note raised that month claims it.
  const splitA = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03', unitIds: [unitA.id] });
  ck('D1 the split note billed it', (await countLines(splitA.id, 'ZZ Repaint')) === 1);
  const splitB = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-03', unitIds: [unitB.id] });
  ck('D2 the other half of the split does not repeat it', (await countLines(splitB.id, 'ZZ Repaint')) === 0);

  // The dangerous call: rebuild the split note that does NOT hold the charge.
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: splitB.id });
  ck('D3 rebuilding the other half still does not pull it in', (await countLines(splitB.id, 'ZZ Repaint')) === 0, 'the already-billed filter was lost');
  ck('D4 nor does it steal the claim from the note that has it', (await claimOf(p2.id)) === splitA.id, `claim moved to ${await claimOf(p2.id)}`);
  ck('D5 the note that legitimately holds it still shows it once', (await countLines(splitA.id, 'ZZ Repaint')) === 1);
  const totalRepaint = await prisma.invoiceLine.count({ where: { invoice: { leaseId: lease.id }, description: { contains: 'ZZ Repaint' } } });
  ck('D6 the tenant is billed for it once across every note', totalRepaint === 1, `appears on ${totalRepaint} lines`);

  console.log('\nE. Meter readings on the same rebuild path are unaffected');
  const meter = await prisma.meter.create({ data: { chargeTypeId: water.id, serialNo: `${SERIAL}1`, units: { create: [{ unitId: unitA.id }] } } });
  await prisma.meterReading.create({ data: { meterId: meter.id, readingStart: '0', readingEnd: '50', periodStart: new Date('2020-03-01'), periodEnd: new Date('2020-03-31'), grossAmount: '500' } });
  const splitA2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-04', unitIds: [unitA.id] });
  ck('E1 the reading is billed on the split note', (await countLines(splitA2.id, 'ZZ Planned Water')) === 1);
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: splitA2.id });
  ck('E2 rebuilding keeps it exactly once', (await countLines(splitA2.id, 'ZZ Planned Water')) === 1);
  const splitB2 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-05', unitIds: [unitB.id] });
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: splitB2.id });
  ck('E3 rebuilding the other half does not take the reading', (await countLines(splitB2.id, 'ZZ Planned Water')) === 0);

  console.log('');
  console.log('F. A charge booked against ONE unit only goes on that unit’s note');
  const p3 = await plan('2020-06', 'ZZ UnitA work', '3000', unitA.id);
  const splitB6 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-06', unitIds: [unitB.id] });
  ck('F1 the other unit’s note does not get it', (await countLines(splitB6.id, 'ZZ UnitA work')) === 0);
  const splitA6 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-06', unitIds: [unitA.id] });
  ck('F2 its own unit’s note gets it exactly once', (await countLines(splitA6.id, 'ZZ UnitA work')) === 1);
  ck('F3 and it is claimed by that note', (await claimOf(p3.id)) === splitA6.id);
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: splitB6.id });
  ck('F4 rebuilding the other unit’s note still does not take it', (await countLines(splitB6.id, 'ZZ UnitA work')) === 0);
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: splitA6.id });
  ck('F5 rebuilding its own note keeps it once', (await countLines(splitA6.id, 'ZZ UnitA work')) === 1);
  // No split means no unit filter at all, so a unit-scoped charge belongs on it.
  const p4 = await plan('2020-07', 'ZZ UnitA whole', '400', unitA.id);
  const whole7 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-07' });
  ck('F6 a whole-lease note carries a unit-scoped charge', (await countLines(whole7.id, 'ZZ UnitA whole')) === 1, `claim ${await claimOf(p4.id)}`);

  console.log('');
  console.log('G. Taking the line off a draft puts the charge back in the queue');
  const p5 = await plan('2020-08', 'ZZ Removable', '1200');
  const inv8 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-08' });
  const removable = (await linesOf(inv8.id)).find((l) => l.description.includes('ZZ Removable'));
  ck('G1 it is on the note to begin with', Boolean(removable) && (await claimOf(p5.id)) === inv8.id);
  await billing.removeLine({ organizationId: orgId, lineId: removable!.id });
  ck('G2 removing the line releases the charge', (await claimOf(p5.id)) === null, 'it would be billed to nobody and could never be re-booked');
  const inv8b = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-08' });
  ck('G3 so a later note for that month can still bill it', (await countLines(inv8b.id, 'ZZ Removable')) === 1);

  console.log('');
  console.log('H. Voiding an ISSUED note releases it too, not just a draft');
  const p6 = await plan('2020-10', 'ZZ Issued extra', '2500');
  const inv10 = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-10' });
  // The demo org gates debit notes, so walk the workflow rather than skipping it.
  await issueInvoice(deps, orgId, inv10.id);
  ck('H1 the issued note carries it', (await claimOf(p6.id)) === inv10.id);
  await billing.voidInvoice({ organizationId: orgId, invoiceId: inv10.id });
  ck('H2 voiding an issued note releases it', (await claimOf(p6.id)) === null);

  console.log('');
  console.log('I. Rebuilding must not delete a hand-raised maintenance recovery');
  const req = await prisma.maintenanceRequest.create({
    data: {
      organizationId: orgId, propertyId: property.id, unitId: unitA.id, leaseId: lease.id,
      title: 'ZZ Broken tap', description: 'ZZ', status: 'COMPLETED',
      costResponsibility: 'TENANT', actualCost: '1800', tenantSharePercent: '100',
    },
  });
  const { invoiceId: recovery } = await maintenance.chargeToTenant({ organizationId: orgId, id: req.id });
  ck('I1 the recovery note carries the repair', (await countLines(recovery, 'ZZ Broken tap')) === 1);
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: recovery });
  // The classifier replaces every CHARGE that is not marked as human intent. The
  // recovery line is exactly that, and losing it is unrecoverable: chargedInvoiceId
  // is stamped once and never cleared, so it could never be raised again.
  ck('I2 rebuilding keeps it', (await countLines(recovery, 'ZZ Broken tap')) === 1, 'the repair cost was silently dropped and can never be re-raised');
  const stillCharged = await prisma.maintenanceRequest.findUniqueOrThrow({ where: { id: req.id }, select: { chargedInvoiceId: true } });
  ck('I3 and the request still points at it', stillCharged.chargedInvoiceId === recovery);
}

async function purgeStale() {
  const meters = await prisma.meter.findMany({ where: { serialNo: { startsWith: SERIAL } }, select: { id: true } });
  const mids = meters.map((m) => m.id);
  if (mids.length) {
    await prisma.meterReading.deleteMany({ where: { meterId: { in: mids } } });
    await prisma.meterUnit.deleteMany({ where: { meterId: { in: mids } } });
    await prisma.meter.deleteMany({ where: { id: { in: mids } } });
  }
  const reqs = await prisma.maintenanceRequest.findMany({ where: { title: 'ZZ Broken tap' }, select: { id: true } });
  if (reqs.length) {
    await prisma.maintenanceTask.deleteMany({ where: { requestId: { in: reqs.map((r) => r.id) } } });
    await prisma.maintenanceRequest.deleteMany({ where: { id: { in: reqs.map((r) => r.id) } } });
  }
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  for (const l of leases) {
    await prisma.plannedCharge.deleteMany({ where: { leaseId: l.id } });
    const invIds = (await prisma.invoice.findMany({ where: { leaseId: l.id }, select: { id: true } })).map((i) => i.id);
    if (invIds.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: invIds } }, { lines: { some: { invoiceId: { in: invIds } } } }] }, select: { id: true, reversesId: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        // Voiding an ISSUED note leaves a reversal entry pointing at the original,
        // so the reversers have to go first or the FK refuses the batch.
        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: invIds } } });
      await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    }
    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: PROP }, 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: TENANT } });
  const ct = await prisma.chargeType.findFirst({ where: { code: CT_CODE }, select: { id: true } });
  if (ct) {
    await prisma.utilityTariff.deleteMany({ where: { chargeTypeId: ct.id } });
    await prisma.chargeType.delete({ where: { id: ct.id } }).catch(() => {});
  }
}

async function cleanup() {
  try { await purgeSmokeApprover(prisma); await purgeSmokeLandlord(prisma, LANDLORD); 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); });
