/**
 * Smoke for settlement reversal (Phase D):
 *  - settle deducts arrears (invoice → PAID) + a charge and parks a refund
 *  - reverseSettlement mirrors the accounting: held restored, invoice re-opened,
 *    Refunds Payable drained, settlement + allocations gone, deposit back to HELD
 *  - a settlement whose refund was already paid (REFUNDED) cannot be reversed
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/reverse-smoke.ts
 */
import 'reflect-metadata';
import type { GlAccountRole } from '@prisma/client';
import { Decimal, sum } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { NumberService } from '../src/common/number.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 = 'ZZREV';

const prisma = new PrismaService();
const ledger = new LedgerService();
const deposits = new DepositsService(prisma, ledger, new NumberService(), 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}`)); };

async function acctBal(orgId: string, role: GlAccountRole): Promise<Decimal> {
  const acc = await prisma.glAccount.findFirst({ where: { organizationId: orgId, role } });
  if (!acc) return new Decimal(0);
  const lines = await prisma.journalLine.findMany({ where: { accountId: acc.id } });
  return sum(lines.filter((l) => l.direction === 'CREDIT').map((l) => l.amount.toString())).minus(
    sum(lines.filter((l) => l.direction === 'DEBIT').map((l) => l.amount.toString())),
  );
}
async function arOut(orgId: string, invoiceId: string): Promise<Decimal> {
  const ar = await prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, role: 'RECEIVABLE' } });
  const lines = await prisma.journalLine.findMany({ where: { accountId: ar.id, invoiceId } });
  return sum(lines.filter((l) => l.direction === 'DEBIT').map((l) => l.amount.toString())).minus(
    sum(lines.filter((l) => l.direction === 'CREDIT').map((l) => l.amount.toString())),
  );
}

async function purge(orgId: string) {
  await purgeSmokeLandlord(prisma, LANDLORD);
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-REV' } }, select: { id: true } });
  const ids = leases.map((l) => l.id);
  const invs = await prisma.invoice.findMany({ where: { OR: [{ number: { startsWith: 'ZZ-REV' } }, { leaseId: { in: ids } }] }, select: { id: true } });
  const invIds = invs.map((i) => i.id);
  const deps = await prisma.deposit.findMany({ where: { OR: [{ leaseId: { in: ids } }, { tenant: { name: 'ZZ Rev Tenant' } }] }, select: { id: true } });
  const depIds = deps.map((d) => d.id);
  const sets = await prisma.depositSettlement.findMany({ where: { depositId: { in: depIds } }, select: { id: true } });
  const setIds = sets.map((s) => s.id);
  if (setIds.length) await prisma.approvalInstance.deleteMany({ where: { documentType: 'DEPOSIT_REFUND', documentId: { in: setIds } } });
  const srcIds = [...ids, ...depIds, ...setIds, ...invIds];
  await prisma.journalLine.deleteMany({ where: { entry: { sourceId: { in: srcIds } } } });
  // Clear the self-FK (a REVERSAL entry points at the entry it reverses) before deleting.
  await prisma.journalEntry.updateMany({ where: { sourceId: { in: srcIds } }, data: { reversesId: null } });
  await prisma.journalEntry.deleteMany({ where: { sourceId: { in: srcIds } } });
  await prisma.depositAllocation.deleteMany({ where: { OR: [{ depositId: { in: depIds } }, { settlementId: { in: setIds } }] } });
  await prisma.depositSettlementLine.deleteMany({ where: { settlementId: { in: setIds } } });
  await prisma.depositSettlement.deleteMany({ where: { id: { in: setIds } } });
  await prisma.deposit.deleteMany({ where: { id: { in: depIds } } });
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
  await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: ids } } });
  await prisma.lease.deleteMany({ where: { id: { in: ids } } });
  const props = await prisma.property.findMany({ where: { organizationId: orgId, name: 'ZZ Rev Property' }, select: { id: true } });
  const propIds = props.map((p) => p.id);
  if (propIds.length) { await prisma.unit.deleteMany({ where: { propertyId: { in: propIds } } }); await prisma.property.deleteMany({ where: { id: { in: propIds } } }); }
  await prisma.tenant.deleteMany({ where: { organizationId: orgId, name: 'ZZ Rev Tenant' } });
}

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;
  await purge(orgId);

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Rev Tenant' } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Rev Property', units: { create: { name: 'ZZ RVU1' } } }, include: { units: true } });
  const lease = await prisma.lease.create({ data: { organizationId: orgId, reference: 'ZZ-REV-L1', tenantId: tenant.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0, units: { create: { unitId: prop.units[0].id } } } });
  const rent = await prisma.chargeType.findFirstOrThrow({ where: { organizationId: orgId, code: 'RENT' } });
  const rm = await prisma.chargeType.findFirstOrThrow({ where: { organizationId: orgId, code: 'RM' } });

  // An ISSUED invoice owing 3000 (AR posted so it has a real outstanding).
  const inv = await prisma.invoice.create({
    data: { organizationId: orgId, leaseId: lease.id, number: 'ZZ-REV-INV1', status: 'ISSUED', currency: 'HKD', billingPeriod: '2020-01', dueDate: new Date('2020-01-15'),
      lines: { create: { kind: 'CHARGE', chargeTypeId: rent.id, description: 'Rent', amount: '3000', sortOrder: 0 } } },
  });
  const income = await prisma.glAccount.findFirstOrThrow({ where: { id: rent.glAccountId ?? '' } });
  const ar = await prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, role: 'RECEIVABLE' } });
  await prisma.$transaction((tx) => ledger.post(tx, { organizationId: orgId, entryDate: new Date('2020-01-01'), sourceType: 'INVOICE', sourceId: inv.id, currency: 'HKD', memo: 'ZZ rev inv',
    lines: [{ accountId: ar.id, direction: 'DEBIT', amount: '3000', invoiceId: inv.id, tenantId: tenant.id }, { accountId: income.id, direction: 'CREDIT', amount: '3000' }] }));
  ck('setup: invoice outstanding = 3000', (await arOut(orgId, inv.id)).toFixed(2) === '3000.00');

  const dep = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '20000' });
  const payableBase = await acctBal(orgId, 'REFUNDS_PAYABLE');

  // Settle: 3000 arrears + 2000 charge → 15000 refund.
  await deposits.settle({ organizationId: orgId, depositId: dep.id, arrears: [{ invoiceId: inv.id, amount: '3000' }], charges: [{ description: 'Cleaning', chargeTypeId: rm.id, amount: '2000' }], settledByUserId: null });
  ck('A1 deposit SETTLED', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id } })).status === 'SETTLED');
  ck('A2 invoice paid (outstanding 0)', (await arOut(orgId, inv.id)).toFixed(2) === '0.00');
  ck('A3 Refunds Payable +15000', (await acctBal(orgId, 'REFUNDS_PAYABLE')).minus(payableBase).toFixed(2) === '15000.00');
  ck('A4 settle-arrears allocation tagged', (await prisma.depositAllocation.count({ where: { depositId: dep.id, settlementId: { not: null } } })) === 1);

  // Reverse.
  await deposits.reverseSettlement({ organizationId: orgId, depositId: dep.id, reversedByUserId: null });
  ck('B1 deposit re-opened to HELD', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep.id } })).status === 'HELD');
  ck('B2 held restored to 20000', (await deposits.settlementData(orgId, dep.id))?.held === '20000.00');
  ck('B3 invoice re-opened (outstanding 3000)', (await arOut(orgId, inv.id)).toFixed(2) === '3000.00');
  ck('B4 invoice status back to ISSUED', (await prisma.invoice.findUniqueOrThrow({ where: { id: inv.id } })).status === 'ISSUED');
  ck('B5 Refunds Payable back to baseline', (await acctBal(orgId, 'REFUNDS_PAYABLE')).toFixed(2) === payableBase.toFixed(2));
  ck('B6 settlement removed', (await prisma.depositSettlement.count({ where: { depositId: dep.id } })) === 0);
  ck('B7 allocations removed', (await prisma.depositAllocation.count({ where: { depositId: dep.id } })) === 0);

  // A paid (REFUNDED) settlement cannot be reversed.
  const lease2 = await prisma.lease.create({ data: { organizationId: orgId, reference: 'ZZ-REV-L2', tenantId: tenant.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2020-01-31'), depositMonths: 0, units: { create: { unitId: prop.units[0].id } } } });
  const dep2 = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease2.id, amount: '8000' });
  await deposits.settle({ organizationId: orgId, depositId: dep2.id, settledByUserId: null });
  await deposits.disburseRefund({ organizationId: orgId, depositId: dep2.id, disbursedByUserId: null });
  let threw = false;
  try { await deposits.reverseSettlement({ organizationId: orgId, depositId: dep2.id }); } catch { threw = true; }
  ck('C1 cannot reverse a REFUNDED deposit', threw);
  ck('C2 deposit stays REFUNDED', (await prisma.deposit.findUniqueOrThrow({ where: { id: dep2.id } })).status === 'REFUNDED');
}

main().catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); }).finally(async () => {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (org) await purge(org.id).catch((e) => console.log('cleanup warn', e instanceof Error ? e.message : e));
  await prisma.$disconnect();
  console.log(`\n==== ${pass} passed, ${fail} failed ====`);
  process.exit(fail > 0 ? 1 : 0);
});
