/**
 * Functional smoke for lease lifecycle transition + deposit carry-over.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/transition-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}`)); };

async function purge(orgId: string) {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-TRN' } }, select: { id: true } });
  const ids = leases.map((l) => l.id);
  if (ids.length) {
    await prisma.deposit.deleteMany({ where: { leaseId: { in: ids } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: ids } } });
    // clear the self-relation before deleting so renewedFromId FK doesn't block
    await prisma.lease.updateMany({ where: { id: { in: ids } }, data: { renewedFromId: null } });
    await prisma.lease.deleteMany({ where: { id: { in: ids } } });
  }
  // Units block the property delete, so they have to go first.
  const props = await prisma.property.findMany({ where: { organizationId: orgId, name: 'ZZ Trn Property' }, select: { id: true } });
  if (props.length) {
    await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
    await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
  }
  await prisma.tenant.deleteMany({ where: { organizationId: orgId, name: { in: ['ZZ Trn Tenant A', 'ZZ Trn Tenant B'] } } });
}

const mkLease = (orgId: string, ref: string, propertyId: string, tenantId: string, status: 'ACTIVE' | 'DRAFT', start: string, end: string, renewedFromId?: string) =>
  prisma.lease.create({ data: { organizationId: orgId, reference: ref, tenantId, status, currency: 'HKD', startDate: new Date(start), endDate: new Date(end), depositMonths: 0, renewedFromId: renewedFromId ?? null } });

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 A = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Trn Tenant A' } });
  const B = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Trn Tenant B' } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Trn Property', units: { create: { name: 'ZZ TU1' } } } });

  // A: old (active, ended) + deposit; renewal (draft, started) same tenant.
  const old1 = await mkLease(orgId, 'ZZ-TRN-OLD1', prop.id, A.id, 'ACTIVE', '2019-01-01', '2020-01-31');
  const dep1 = await prisma.deposit.create({ data: { organizationId: orgId, number: `ZZ-TRND1-${Date.now()}`, tenantId: A.id, leaseId: old1.id, status: 'HELD', amount: '20000', currency: 'HKD', receivedDate: new Date('2019-01-01') } });
  const new1 = await mkLease(orgId, 'ZZ-TRN-NEW1', prop.id, A.id, 'DRAFT', '2020-02-01', '2021-01-31', old1.id);
  // B: old (active, ended); renewal (draft, FUTURE start) same tenant.
  const old2 = await mkLease(orgId, 'ZZ-TRN-OLD2', prop.id, A.id, 'ACTIVE', '2019-01-01', '2020-01-31');
  const new2 = await mkLease(orgId, 'ZZ-TRN-NEW2', prop.id, A.id, 'DRAFT', '2100-02-01', '2101-01-31', old2.id);
  // C: old (active, ended) + deposit; renewal (draft, started) DIFFERENT tenant.
  const old3 = await mkLease(orgId, 'ZZ-TRN-OLD3', prop.id, A.id, 'ACTIVE', '2019-01-01', '2020-01-31');
  const dep3 = await prisma.deposit.create({ data: { organizationId: orgId, number: `ZZ-TRND3-${Date.now()}`, tenantId: A.id, leaseId: old3.id, status: 'HELD', amount: '15000', currency: 'HKD', receivedDate: new Date('2019-01-01') } });
  const new3 = await mkLease(orgId, 'ZZ-TRN-NEW3', prop.id, B.id, 'DRAFT', '2020-02-01', '2021-01-31', old3.id);

  console.log('Running transitionLeases (asOf = now)…\n');
  const res = await billing.transitionLeases({ organizationId: orgId, asOf: new Date() });
  console.log('result:', JSON.stringify(res), '\n');

  const st = async (id: string) => (await prisma.lease.findUniqueOrThrow({ where: { id }, select: { status: true } })).status;
  const depLease = async (id: string) => (await prisma.deposit.findUniqueOrThrow({ where: { id }, select: { leaseId: true } })).leaseId;

  console.log('A. Old lease ends, same-tenant renewal activates, deposit carries over');
  ck('A1 old1 ENDED', (await st(old1.id)) === 'ENDED');
  ck('A2 renewal new1 ACTIVE', (await st(new1.id)) === 'ACTIVE');
  ck('A3 deposit moved to renewal', (await depLease(dep1.id)) === new1.id);

  console.log('B. Renewal with a future start is NOT activated (but old still ends)');
  ck('B1 old2 ENDED', (await st(old2.id)) === 'ENDED');
  ck('B2 future renewal new2 stays DRAFT', (await st(new2.id)) === 'DRAFT');

  console.log('C. Different-tenant renewal: deposit is NOT moved');
  ck('C1 old3 ENDED', (await st(old3.id)) === 'ENDED');
  ck('C2 deposit stays on old lease (different tenant)', (await depLease(dep3.id)) === old3.id);
}

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