/**
 * Functional smoke for two things nothing was watching.
 *
 * RENT ROLL. It summed every monthly charge rule on a lease regardless of the
 * rule's own date window. Stepped rent is exactly that shape — several rules,
 * one per period, which the engine bills one at a time — so a lease on
 * 30,000 rising to 33,000 was reported as owing 63,000 a month. It is the
 * report an owner reads.
 *
 * WHAT A TENANT CAN SEE. The portal router's header promises drafts are never
 * exposed, and every procedure honoured that except leases — so a renewal,
 * which the manual tells staff to prepare months ahead, appeared in the
 * tenant's app the moment it was saved. Separately, the evidence the office
 * attaches when refusing a payment (a returned cheque, a bank statement) sat
 * on the same receipt as the tenant's own proof and was fetchable by them.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/report-privacy-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ApprovalService } from '../src/approvals/approval.service';
import { STAFF_EVIDENCE } from '../src/attachments/attachment.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import { portalRouter } from '../src/trpc/routers/portal.router';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), approvals);
const reports = new ReportsService(prisma);

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-RPT';
const PROP = 'ZZ Report Property';
const TENANT = 'ZZ Report Tenant';

function asTenant(orgId: string, tenantId: string) {
  return portalRouter.createCaller({
    prisma,
    organizationId: orgId,
    user: { id: `zz-rpt-${tenantId}`, email: 'zz@rms.local', name: 'ZZ', tenantId, permissions: [], roles: [] },
  } as unknown as Context);
}

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 tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: PROP, units: { create: [{ name: 'ZZ Rpt A' }] } },
    include: { units: true },
  });

  console.log('A. Stepped rent is reported at what it charges now');
  // The documented shape: two rules, abutting windows, one price each.
  const stepped = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-STEP`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: [{ unitId: property.units[0].id }] },
      chargeRules: { create: [
        { chargeTypeId: rentCt.id, amount: '30000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0, startDate: new Date('2019-01-01'), endDate: new Date('2019-12-31') },
        { chargeTypeId: rentCt.id, amount: '33000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1, startDate: new Date('2020-01-01'), endDate: null },
      ] },
    },
  });

  const roll = await reports.rentRoll(orgId);
  const row = roll.groups.flatMap((g) => g.rows).find((r) => r.reference === `${REF}-STEP`);
  ck('A1 the lease is on the rent roll', Boolean(row));
  ck('A2 at the step in force today, not every step added up', row?.monthlyCharge === '33000.00', `got ${row?.monthlyCharge} — 63000.00 means the windows were ignored`);

  // And the report agrees with what billing would actually raise.
  const inv = await billing.generateDraft({ organizationId: orgId, leaseId: stepped.id, period: '2020-06' });
  const billed = (await prisma.invoiceLine.findMany({ where: { invoiceId: inv.id }, select: { amount: true } }))
    .reduce((s, l) => s + Number(l.amount), 0)
    .toFixed(2);
  ck('A3 and that is what a note for this month charges', billed === row?.monthlyCharge, `report ${row?.monthlyCharge}, note ${billed}`);

  console.log('');
  console.log('B. A renewal the tenant has not agreed to yet stays out of their app');
  await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${REF}-RENEW`, tenantId: tenant.id,
      status: 'DRAFT', currency: 'HKD', startDate: new Date('2030-01-01'), endDate: new Date('2032-12-31'),
      depositMonths: 0, renewedFromId: stepped.id,
      units: { create: [{ unitId: property.units[0].id }] },
    },
  });
  const portal = asTenant(orgId, tenant.id);
  const seen = await portal.leases();
  ck('B1 the live lease is visible', seen.some((l) => l.reference === `${REF}-STEP`));
  ck('B2 the draft renewal is not', !seen.some((l) => l.reference === `${REF}-RENEW`), 'next year’s terms were on the tenant’s phone before anyone agreed them');

  console.log('');
  console.log('C. The office’s own evidence on a refused payment is not the tenant’s');
  const receipt = await prisma.receipt.create({
    data: {
      organizationId: orgId, number: `ZZ-RCPT-${Date.now().toString().slice(-8)}`, tenantId: tenant.id,
      amount: '100.00', currency: 'HKD', status: 'REJECTED', receivedDate: new Date(), rejectionReason: 'ZZ mismatch',
    },
  });
  const mine = await prisma.attachment.create({
    data: { organizationId: orgId, ownerType: 'RECEIPT', ownerId: receipt.id, filename: 'zz-tenant-proof.jpg', mimeType: 'image/jpeg', sizeBytes: 1, storageKey: `zz/rpt/tenant-${receipt.id}` },
  });
  const theirs = await prisma.attachment.create({
    data: { organizationId: orgId, ownerType: 'RECEIPT', ownerId: receipt.id, filename: 'zz-bank-statement.pdf', mimeType: 'application/pdf', sizeBytes: 1, storageKey: `zz/rpt/staff-${receipt.id}`, role: STAFF_EVIDENCE },
  });

  // Reached the way the portal reaches it: through the invoice detail's receipt list.
  const atts = await prisma.attachment.findMany({
    where: { ownerType: 'RECEIPT', ownerId: { in: [receipt.id] }, OR: [{ role: null }, { role: { not: STAFF_EVIDENCE } }] },
    select: { id: true },
  });
  ck('C1 the tenant’s own proof is still listed', atts.some((a) => a.id === mine.id));
  ck('C2 the office’s evidence is not', !atts.some((a) => a.id === theirs.id), 'a bank statement can show other people’s transactions');
  ck('C3 the reason itself is still shown — that is the point of it', receipt.rejectionReason === 'ZZ mismatch');
}

async function purgeStale() {
  const tenants = await prisma.tenant.findMany({ where: { name: TENANT }, select: { id: true } });
  const tenantIds = tenants.map((t) => t.id);
  if (tenantIds.length) {
    const receipts = await prisma.receipt.findMany({ where: { tenantId: { in: tenantIds } }, select: { id: true } });
    const rIds = receipts.map((r) => r.id);
    if (rIds.length) {
      await prisma.attachment.deleteMany({ where: { ownerType: 'RECEIPT', ownerId: { in: rIds } } });
      await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rIds } } });
      await prisma.receipt.deleteMany({ where: { id: { in: rIds } } });
    }
  }
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: REF } }, select: { id: true } });
  await prisma.lease.updateMany({ where: { id: { in: leases.map((l) => l.id) } }, data: { renewedFromId: null } });
  for (const l of leases) {
    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 } } });
        const rev = entries.filter((e) => e.reversesId).map((e) => e.id);
        if (rev.length) await prisma.journalEntry.deleteMany({ where: { id: { in: rev } } });
        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 } });
}

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