/**
 * Functional smoke for the back office recording a payment with its proof, and
 * for the guard that keeps that from double-crediting a note the tenant has
 * already declared a payment on. Standalone (writes to the dev DB, self-cleans).
 *
 * The flow under test is record → attach proof → approve, in that order: the
 * proof must exist before anything reaches the ledger, and approving is what
 * actually settles the note.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/payment-proof-smoke.ts
 */
import 'reflect-metadata';
import { issueInvoice, purgeSmokeApprover } from './_smoke-approval';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } from '@rms/domain';
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 { PaymentsService } from '../src/payments/payments.service';
import { ReportsService } from '../src/reports/reports.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { invoiceArState } from '../src/billing/invoice-ar';
import type { Prisma } from '@prisma/client';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

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

const prisma = new PrismaService();
const ledger = new LedgerService();
const numbers = new NumberService();
const events = new EventEmitter2();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, numbers, events, approvals);
const payments = new PaymentsService(prisma, ledger, numbers, events);
const reports = new ReportsService(prisma);

let pass = 0, fail = 0;
function check(name: string, cond: boolean, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}`); } else { fail++; console.log(`  ✗ ${name}   ${detail}`); }
}
async function expectThrow(name: string, fn: () => Promise<unknown>, contains: string) {
  try { await fn(); check(name, false, '(expected a throw)'); }
  catch (e) { const m = e instanceof Error ? e.message : String(e); check(name, m.includes(contains), `wrong message: "${m}"`); }
}

const createdInvoiceIds: string[] = [];
const createdReceiptIds: string[] = [];
let fx: { tenantId: string; propertyId: string; unitIds: string[]; leaseIds: string[]; orgId: string } | null = null;
// The reports use Hong Kong day boundaries, so "today" has to be the Hong
// Kong date. A UTC date is a day behind between midnight and 08:00 HKT, and
// every entry posted in those hours falls outside the window it asks for.
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Hong_Kong' });

const db = prisma as unknown as Prisma.TransactionClient;
const outstandingOf = async (orgId: string, invoiceId: string) => (await invoiceArState(db, orgId, invoiceId)).outstanding;
const statusOf = async (id: string) => (await prisma.invoice.findUniqueOrThrow({ where: { id }, select: { status: true } })).status;

/** The proof itself. The multipart route is not reachable from a script, so the
 *  row is written directly — what matters here is the ownerType/ownerId key the
 *  debit-note screen joins on, not the bytes. */
async function attachProof(orgId: string, receiptId: string, name: string) {
  return prisma.attachment.create({
    data: {
      organizationId: orgId, ownerType: 'RECEIPT', ownerId: receiptId,
      filename: name, mimeType: 'image/jpeg', sizeBytes: 1024,
      storageKey: `zz-smoke/${receiptId}/${name}`,
    },
  });
}

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('No organization seeded.');
  const orgId = org.id;
  const chargeType = await prisma.chargeType.findFirst({ where: { organizationId: orgId, glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!chargeType) throw new Error('No charge type with a GL account.');

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Proof Tenant' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Proof Property', units: { create: [{ name: 'ZZ P1' }, { name: 'ZZ P2' }, { name: 'ZZ P3' }] } },
    include: { units: true },
  });
  const mkLease = (unitId: string, tag: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-PRF-${tag}-${property.id.slice(-5)}`,
        tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
        startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: { unitId } },
        chargeRules: { create: { chargeTypeId: chargeType.id, amount: '1000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
      },
    });
  const leaseA = await mkLease(property.units[0].id, 'A');
  const leaseB = await mkLease(property.units[1].id, 'B');
  const leaseC = await mkLease(property.units[2].id, 'C');
  fx = { tenantId: tenant.id, propertyId: property.id, unitIds: property.units.map((u) => u.id), leaseIds: [leaseA.id, leaseB.id, leaseC.id], orgId };

  const issued = async (leaseId: string, period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId, period });
    createdInvoiceIds.push(inv.id);
    await issueInvoice({ prisma, billing, approvals }, orgId, inv.id);
    return inv.id;
  };
  console.log('Fixture: three leases at rent 1000, one issued note each\n');

  console.log('A. Record → attach proof → approve');
  const invA = await issued(leaseA.id, '2099-01');
  const rA = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '1000', allocations: [{ invoiceId: invA, amount: '1000' }],
  });
  createdReceiptIds.push(rA.id);
  const entriesBefore = await prisma.journalEntry.count({ where: { sourceType: 'RECEIPT', sourceId: rA.id } });
  check('A1 recording alone leaves the receipt PENDING and posts nothing', rA.status === 'PENDING' && entriesBefore === 0, `status ${rA.status}, entries ${entriesBefore}`);
  check('A2 the note is untouched until the receipt is approved', (await statusOf(invA)) === 'ISSUED', `got ${await statusOf(invA)}`);

  const proof = await attachProof(orgId, rA.id, 'bank-in.jpg');
  const found = await prisma.attachment.findFirst({ where: { ownerType: 'RECEIPT', ownerId: rA.id }, select: { id: true } });
  check('A3 the proof is reachable by the receipt key the note screen joins on', found?.id === proof.id);

  await payments.approve({ organizationId: orgId, receiptId: rA.id });
  const rAafter = await prisma.receipt.findUniqueOrThrow({ where: { id: rA.id }, select: { status: true } });
  check('A4 the receipt is APPROVED', rAafter.status === 'APPROVED', `got ${rAafter.status}`);
  check('A5 the note reads PAID', (await statusOf(invA)) === 'PAID', `got ${await statusOf(invA)}`);
  const entry = await prisma.journalEntry.findFirst({ where: { sourceType: 'RECEIPT', sourceId: rA.id }, include: { lines: true } });
  const dr = entry?.lines.filter((l) => l.direction === 'DEBIT').reduce((s, l) => s.plus(l.amount.toString()), new Decimal(0)) ?? new Decimal(0);
  const cr = entry?.lines.filter((l) => l.direction === 'CREDIT').reduce((s, l) => s.plus(l.amount.toString()), new Decimal(0)) ?? new Decimal(0);
  check('A6 one balanced entry for the amount received', Boolean(entry) && dr.equals(1000) && cr.equals(1000), `DR ${dr} CR ${cr}`);
  check('A7 the proof survives approval', (await prisma.attachment.count({ where: { ownerType: 'RECEIPT', ownerId: rA.id } })) === 1);

  console.log('\nB. A short payment settles part, not all');
  const invB = await issued(leaseB.id, '2099-01');
  const rB1 = await payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '400', allocations: [{ invoiceId: invB, amount: '400' }] });
  createdReceiptIds.push(rB1.id);
  await payments.approve({ organizationId: orgId, receiptId: rB1.id });
  check('B1 the note is PARTIALLY_PAID, not falsely PAID', (await statusOf(invB)) === 'PARTIALLY_PAID', `got ${await statusOf(invB)}`);
  check('B2 outstanding is the remainder', (await outstandingOf(orgId, invB)).equals(600), `got ${await outstandingOf(orgId, invB)}`);
  const rB2 = await payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '600', allocations: [{ invoiceId: invB, amount: '600' }] });
  createdReceiptIds.push(rB2.id);
  await payments.approve({ organizationId: orgId, receiptId: rB2.id });
  check('B3 the remainder settles it', (await statusOf(invB)) === 'PAID', `got ${await statusOf(invB)}`);

  console.log('\nC. The same bank-in declared twice cannot be credited twice');
  const invC = await issued(leaseC.id, '2099-01');
  // The tenant declares the payment from the portal…
  const tenantReceipt = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: invC, amount: '1000' });
  createdReceiptIds.push(tenantReceipt.id);
  await attachProof(orgId, tenantReceipt.id, 'tenant-slip.jpg');
  // …and the office, not seeing it, records the same money against the same note.
  const officeReceipt = await payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '1000', allocations: [{ invoiceId: invC, amount: '1000' }] });
  createdReceiptIds.push(officeReceipt.id);
  await attachProof(orgId, officeReceipt.id, 'office-slip.jpg');
  check('C1 both are accepted while unposted — recording is ledger-blind by design', tenantReceipt.status === 'PENDING' && officeReceipt.status === 'PENDING');

  await payments.approve({ organizationId: orgId, receiptId: tenantReceipt.id });
  check('C2 the first approval settles the note', (await statusOf(invC)) === 'PAID', `got ${await statusOf(invC)}`);

  await expectThrow('C3 the second approval is refused', () =>
    payments.approve({ organizationId: orgId, receiptId: officeReceipt.id }), 'exceeds its outstanding');
  const stillPending = await prisma.receipt.findUniqueOrThrow({ where: { id: officeReceipt.id }, select: { status: true } });
  check('C4 the refused receipt is still PENDING, so it can be rejected', stillPending.status === 'PENDING', `got ${stillPending.status}`);
  check('C5 outstanding lands exactly at zero, never negative', (await outstandingOf(orgId, invC)).equals(0), `got ${await outstandingOf(orgId, invC)}`);
  const credits = await prisma.journalEntry.count({ where: { sourceType: 'RECEIPT', sourceId: { in: [tenantReceipt.id, officeReceipt.id] } } });
  check('C6 exactly one receipt entry reached the ledger', credits === 1, `got ${credits}`);

  console.log('\nD. The books still balance');
  const tb = await reports.trialBalance(orgId, today);
  check('D1 every currency balances (DR == CR)', tb.groups.every((g) => g.balanced), JSON.stringify(tb.groups.map((g) => [g.currency, g.balanced])));
}

async function cleanup() {
  await purgeSmokeApprover(prisma);
  await purgeSmokeLandlord(prisma, LANDLORD);
  try {
    if (createdReceiptIds.length) await prisma.attachment.deleteMany({ where: { ownerType: 'RECEIPT', ownerId: { in: createdReceiptIds } } });
    const ids = createdInvoiceIds;
    const allSrc = [...ids, ...createdReceiptIds];
    if (allSrc.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: allSrc } }, { lines: { some: { invoiceId: { in: ids } } } }] }, select: { id: true, reversesId: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        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 } } });
      }
    }
    if (createdReceiptIds.length) {
      await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: createdReceiptIds } } });
      await prisma.receipt.deleteMany({ where: { id: { in: createdReceiptIds } } });
    }
    if (ids.length) await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
    if (fx) {
      for (const id of fx.leaseIds) await prisma.lease.delete({ where: { id } }).catch(() => {});
      await prisma.unit.deleteMany({ where: { id: { in: fx.unitIds } } });
      await prisma.property.delete({ where: { id: fx.propertyId } }).catch(() => {});
      await prisma.tenant.delete({ where: { id: fx.tenantId } }).catch(() => {});
    }
    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); });
