/**
 * Smoke for deposits.awaitingSettlement: a HELD deposit on an ENDED lease is
 * surfaced; one on an ACTIVE lease is not.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/awaiting-smoke.ts
 */
import 'reflect-metadata';
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 = 'ZZAWT';

const prisma = new PrismaService();
const deposits = new DepositsService(prisma, new LedgerService(), 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 purge(orgId: string) {
  await purgeSmokeLandlord(prisma, LANDLORD);
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-AWT' } }, select: { id: true } });
  const ids = leases.map((l) => l.id);
  if (ids.length) {
    const deps = await prisma.deposit.findMany({ where: { leaseId: { in: ids } }, select: { id: true } });
    const depIds = deps.map((d) => d.id);
    await prisma.journalLine.deleteMany({ where: { entry: { sourceId: { in: [...ids, ...depIds] } } } });
    await prisma.journalEntry.deleteMany({ where: { sourceId: { in: [...ids, ...depIds] } } });
    await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
    await prisma.deposit.deleteMany({ where: { id: { in: depIds } } });
    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 Awt 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 Awt 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 Awt Tenant' } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Awt Property', units: { create: { name: 'ZZ AU1' } } }, include: { units: true } });
  const mk = (ref: string, status: 'ACTIVE' | 'ENDED' | 'TERMINATED', end: string, extra: Record<string, unknown> = {}) =>
    prisma.lease.create({ data: { organizationId: orgId, reference: ref, tenantId: tenant.id, status, currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date(end), depositMonths: 0, units: { create: { unitId: prop.units[0].id } }, ...extra } });

  const endedLease = await mk('ZZ-AWT-ENDED', 'ENDED', '2020-01-31');
  // Genuinely still running — its term has not passed.
  const runningLease = await mk('ZZ-AWT-RUNNING', 'ACTIVE', '2099-12-31');
  // Term is over but the nightly job hasn't flipped the stored status yet.
  const lapsedLease = await mk('ZZ-AWT-LAPSED', 'ACTIVE', '2020-01-31');
  const terminatedLease = await mk('ZZ-AWT-TERM', 'TERMINATED', '2099-12-31', { terminatedAt: new Date('2021-06-15') });

  const dEnded = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: endedLease.id, amount: '15000' });
  const dRunning = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: runningLease.id, amount: '9000' });
  const dLapsed = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lapsedLease.id, amount: '8000' });
  const dTerm = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: terminatedLease.id, amount: '7000' });

  const list = await deposits.awaitingSettlement(orgId);
  const ended = list.find((x) => x.id === dEnded.id);

  ck('HELD deposit on ENDED lease is listed', !!ended);
  ck('held amount derived from ledger = 15000.00', ended?.held === '15000.00', `got ${ended?.held}`);
  ck('leaseRef surfaced', ended?.leaseRef === 'ZZ-AWT-ENDED', `got ${ended?.leaseRef}`);
  ck('endDate surfaced', !!ended?.endDate);
  ck('HELD deposit on a still-running lease is NOT listed', !list.find((x) => x.id === dRunning.id));
  ck('HELD deposit on an expired-but-unflipped lease IS listed', !!list.find((x) => x.id === dLapsed.id));
  ck('HELD deposit on a TERMINATED lease is listed', !!list.find((x) => x.id === dTerm.id));
  ck(
    'a terminated lease reports its termination date, not the contracted end',
    list.find((x) => x.id === dTerm.id)?.endDate?.toISOString().slice(0, 10) === '2021-06-15',
    String(list.find((x) => x.id === dTerm.id)?.endDate),
  );
}

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