/**
 * Functional smoke for the printed receipt.
 *
 * An approved payment has a receipt, modelled on the ERP's: the debit notes it
 * settled and how much of each, the total in words, what was received and how,
 * and the settlement method's remark. This proves the figures for a payment
 * over two notes, for one paid over what was owed (the excess held under a
 * deposit receipt, printed on this receipt and never on one of its own), and
 * for money paid ahead of the notes; that the receipt is headed as the note it
 * paid was, frozen, while a deposit receipt reads its lease today; that only an
 * approved or bounced payment has one, a bounced one stamped; that the proof
 * uploaded with the payment follows it — never the office's private evidence —
 * and a PDF proof's own pages are joined on; and that the tenant's portal shows
 * what was paid, and lists the deposit receipts paid ahead.
 *
 * Its own organisation and settlement method. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/receipt-document-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { PDFDocument } from 'pdf-lib';
import { ApprovalService } from '../src/approvals/approval.service';
import { STAFF_EVIDENCE } from '../src/attachments/attachment.service';
import { StorageService } from '../src/attachments/storage.service';
import { BillingService } from '../src/billing/billing.service';
import { amountInWords, integerInWords } from '../src/common/amount-words';
import { NumberService } from '../src/common/number.service';
import { DEFAULT_TEMPLATES } from '../src/documents/default-templates';
import { DocumentService } from '../src/documents/document.service';
import type { PdfService } from '../src/documents/pdf.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { portalRouter } from '../src/trpc/routers/portal.router';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const ledger = new LedgerService();
const numbers = new NumberService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, ledger, numbers, new EventEmitter2(), approvals);
const payments = new PaymentsService(prisma, ledger, numbers, new EventEmitter2());
const storage = new StorageService(new ConfigService());
// The receipt's own page needs no Chromium here: a one-page stand-in, so what
// is checked is that the proof's pages are joined on after it.
const onePage = async () => {
  const doc = await PDFDocument.create();
  doc.addPage();
  return Buffer.from(await doc.save());
};
const documents = new DocumentService(prisma, storage, { render: onePage } as unknown as PdfService);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
const refused = (p: Promise<unknown>) => p.then(() => '', (e: Error) => e.message);

const ORG_CODE = 'ZZ-RCD-ORG';
const METHOD_CODE = 'ZZ_RCD_CHQ';
const REMARK = 'Cheque deposit (Not valid until cheque is cleared)';
const savedKeys: string[] = [];

async function main() {
  await purge();

  console.log('W. The total in words');
  ck('W1 the ERP sample\'s figure', amountInWords('872947.00', 'HKD') === 'HONG KONG DOLLARS EIGHT HUNDRED AND SEVENTY TWO THOUSAND NINE HUNDRED AND FORTY SEVEN ONLY', amountInWords('872947.00', 'HKD'));
  ck('W2 cents, another currency, and "and" before a last group under a hundred', amountInWords('1005.50', 'SGD') === 'SINGAPORE DOLLARS ONE THOUSAND AND FIVE AND CENTS FIFTY ONLY', amountInWords('1005.50', 'SGD'));
  ck('W3 cents alone', amountInWords('0.25', 'HKD') === 'HONG KONG DOLLARS ZERO AND CENTS TWENTY FIVE ONLY', amountInWords('0.25', 'HKD'));
  ck('W4 round millions', amountInWords('1000000', 'HKD') === 'HONG KONG DOLLARS ONE MILLION ONLY');
  ck('W5 teens, hundreds, skipped groups', integerInWords(12) === 'TWELVE' && integerInWords(115) === 'ONE HUNDRED AND FIFTEEN' && integerInWords(2_000_013) === 'TWO MILLION AND THIRTEEN' && integerInWords(40_300) === 'FORTY THOUSAND THREE HUNDRED',
    JSON.stringify([integerInWords(115), integerInWords(2_000_013), integerInWords(40_300)]));

  // ── Fixture ──
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Receipt Org', address: '6/F, ZZ Plaza', tel: '2866 0000' } })).id;
  for (const [docType, prefix] of [['INVOICE', 'ZRN-'], ['RECEIPT', 'ZRR-'], ['DEPOSIT_RECEIPT', 'ZRD-'], ['DEPOSIT', 'ZRP-'], ['LEASE', 'ZRL-']]) {
    await prisma.numberSequence.create({ data: { organizationId: orgId, docType, prefix, padding: 4 } });
  }
  const gl: Record<string, string> = {};
  for (const [code, name, type, role] of [['1000', 'Bank', 'ASSET', 'BANK'], ['1100', 'AR', 'ASSET', 'RECEIVABLE'], ['2300', 'Deposits Held', 'LIABILITY', 'DEPOSITS_HELD'], ['2350', 'Tenant Credit', 'LIABILITY', 'TENANT_CREDIT'], ['4000', 'Rental Income', 'INCOME', null]] as const) {
    gl[code] = (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type, role } })).id;
  }
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: gl['4000'] } });
  const landlord = await prisma.landlord.create({ data: { organizationId: orgId, code: 'ZZRCD', name: 'ZZ Receipt Holdings Limited', address: '1 ZZ Landlord Street' } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Receipt Tenant', attention: 'Miss ZZ', phone: '6292 0000' } });
  await prisma.tenantCode.create({ data: { organizationId: orgId, tenantId: tenant.id, landlordId: landlord.id, code: 'ZZRCD01' } });
  // Billed under the landlord company: the notes freeze its heading as issued.
  const property = await prisma.property.create({
    data: { organizationId: orgId, landlordId: landlord.id, letterheadSource: 'LANDLORD', name: 'ZZ Receipt Plaza', address: '9 ZZ Road, Kowloon Bay', units: { create: ['A', 'B', 'C'].map((name) => ({ name })) } },
    include: { units: true },
  });
  const mkLease = (ref: string, units: number[]) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-RCD-${ref}`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
        startDate: new Date('2025-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: units.map((i) => ({ unitId: property.units[i].id })) },
        chargeRules: { create: [{ chargeTypeId: rent.id, amount: '6112', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
      },
    });
  const L1 = await mkLease('L1', [0, 1]);
  const L2 = await mkLease('L2', [2]);
  const cheque = await prisma.settlementMethod.create({ data: { code: METHOD_CODE, nameEn: 'Cheque', requiresReference: true, receiptRemark: REMARK } });

  const issue = async (period: string, day: string) => {
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId: L1.id, period });
    const inv = await billing.issue({ organizationId: orgId, invoiceId: draft.id });
    await prisma.invoice.update({ where: { id: inv.id }, data: { issueDate: new Date(`${day}T10:00:00+08:00`) } });
    return inv;
  };
  const n1 = await issue('2025-08', '2025-08-01');
  const n2 = await issue('2025-09', '2025-09-01');
  // The heading changes after the notes went out; their receipts must not follow.
  await prisma.property.update({ where: { id: property.id }, data: { letterheadSource: 'ORGANIZATION' } });

  const proof = async (receiptId: string, filename: string, mimeType: string, bytes: Buffer, role: string | null = null) => {
    const ext = filename.split('.').pop() ?? 'bin';
    const storageKey = await storage.save(bytes, ext);
    savedKeys.push(storageKey);
    return prisma.attachment.create({ data: { organizationId: orgId, ownerType: 'RECEIPT', ownerId: receiptId, filename, mimeType, sizeBytes: bytes.length, storageKey, role } });
  };
  const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
  const twoPages = async () => {
    const doc = await PDFDocument.create();
    doc.addPage();
    doc.addPage();
    return Buffer.from(await doc.save());
  };

  // A cheque over both notes, the office's entry; its proofs.
  const rA = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '9112', settlementMethodId: cheque.id, reference: 'BOC 001',
    receivedDate: new Date('2025-09-20'), note: 'internal: chased twice',
    allocations: [{ invoiceId: n1.id, amount: '6112' }, { invoiceId: n2.id, amount: '3000' }],
  });
  await payments.approve({ organizationId: orgId, receiptId: rA.id });
  await proof(rA.id, 'cheque-slip.png', 'image/png', PNG);
  await proof(rA.id, 'bank-advice.pdf', 'application/pdf', await twoPages());
  await proof(rA.id, 'iphone.heic', 'image/heic', Buffer.from('heic'));
  await proof(rA.id, 'zz-office-bank-statement.png', 'image/png', PNG, STAFF_EVIDENCE);

  console.log('\nC. A payment over two notes');
  const a = await documents.receiptContext(orgId, rA.id);
  ck('C1 each note it settled: number, issue day, and the part paid', JSON.stringify(a.invoices) === JSON.stringify([
    { number: n1.number, date: '2025-08-01', amount: '6112.00' },
    { number: n2.number, date: '2025-09-01', amount: '3000.00' },
  ]), JSON.stringify(a.invoices));
  ck('C2 settled, applied and received are all 9,112, nothing in excess', a.total === '9112.00' && a.applied === '9112.00' && a.actual === '9112.00' && a.excess.length === 0 && !a.advance,
    JSON.stringify([a.total, a.applied, a.actual, a.excess]));
  ck('C3 the total in words', a.words === 'HONG KONG DOLLARS NINE THOUSAND ONE HUNDRED AND TWELVE ONLY', a.words);
  ck('C4 the day received, how, the cheque number, and the method\'s remark', a.receipt.date === '2025-09-20' && a.receipt.method === 'Cheque' && a.receipt.reference === 'BOC 001' && a.receipt.remark === REMARK && a.receipt.symbol === 'HK$',
    JSON.stringify(a.receipt));
  ck('C5 the tenant: name, code under the landlord, attention, phone', a.tenant.name === 'ZZ Receipt Tenant' && a.tenant.code === 'ZZRCD01' && a.tenant.attention === 'Miss ZZ' && a.tenant.phone === '6292 0000', JSON.stringify(a.tenant));
  ck('C6 addressed to the premises the notes were for', JSON.stringify(a.property.addressLines) === JSON.stringify(['A, B, ZZ Receipt Plaza', '9 ZZ Road', 'Kowloon Bay']), JSON.stringify(a.property.addressLines));
  ck('C7 headed as the notes were frozen — the landlord — though the building now prints the organisation', a.org.name === 'ZZ Receipt Holdings Limited', a.org.name);

  console.log('\nH. The page');
  const html = (await documents.receiptHtml(orgId, rA.id)).html;
  const has = (s: string) => html.includes(s);
  ck('H1 receipt number, the ERP\'s date, the notes and the total', has(rA.number) && has('2025SEP20') && has(n1.number!) && has('2025AUG01') && has('9,112.00'));
  ck('H2 the words, the cheque number and the remark', has('SAY TOTAL HONG KONG DOLLARS NINE THOUSAND ONE HUNDRED AND TWELVE ONLY') && has('Cheque No.') && has('BOC 001') && has(REMARK));
  ck('H3 the receipt\'s own note is the office\'s, and not printed', !has('chased twice'));
  ck('H4 not stamped while the payment stands', !has('DISHONOURED'));
  const { appendPdfs } = await documents.receiptHtml(orgId, rA.id);
  ck('H5 the proof follows: the photo drawn in', has(`Payment proof — ${rA.number}`) && has('src="data:image/png;base64,') && has('cheque-slip.png'));
  ck('H6 a PDF proof is named and its pages joined on', has('bank-advice.pdf — its pages follow at the end of this receipt') && appendPdfs.length === 1 && appendPdfs[0].filename === 'bank-advice.pdf');
  ck('H7 a HEIC photo the renderer cannot draw is named, not drawn', has('iphone.heic') && !has('data:image/heic'));
  ck('H8 the office\'s private evidence is not on the tenant\'s receipt', !has('zz-office-bank-statement.png'));
  const pdf = await PDFDocument.load(await documents.receiptPdf(orgId, rA.id));
  ck('H9 the PDF: the receipt\'s page, then the bank advice\'s two', pdf.getPageCount() === 3, String(pdf.getPageCount()));

  console.log('\nO. Paid over what was owed');
  const rO = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: tenant.id, amount: '3112', settlementMethodId: cheque.id, reference: 'BOC 002', receivedDate: new Date('2025-09-25'),
    allocations: [{ invoiceId: n2.id, amount: '3112' }], overpayment: { amount: '888', leaseId: L1.id },
  });
  await payments.approve({ organizationId: orgId, receiptId: rO.id });
  await proof(rO.id, 'second-cheque.png', 'image/png', PNG);
  const drO = await prisma.receipt.findFirstOrThrow({ where: { sourceReceiptId: rO.id } });
  const o = await documents.receiptContext(orgId, rO.id);
  ck('O1 applied to the note 3,112; received 4,000; the 888 excess named', o.applied === '3112.00' && o.actual === '4000.00' && JSON.stringify(o.excess) === JSON.stringify([{ number: drO.number, amount: '888.00' }]),
    JSON.stringify([o.applied, o.actual, o.excess]));
  ck('O2 the words are the total settled', o.total === '3112.00' && o.words === 'HONG KONG DOLLARS THREE THOUSAND ONE HUNDRED AND TWELVE ONLY', o.words);
  const oHtml = (await documents.receiptHtml(orgId, rO.id)).html;
  ck('O3 the page says where the excess went', oHtml.includes(`held as advance payment under ${drO.number}`) && oHtml.includes('4,000.00'));
  ck('O4 one bank-in, one receipt: the excess has none of its own', (await refused(documents.receiptContext(orgId, drO.id))) === 'The overpaid part of a payment is printed on the receipt for that payment');
  ck('O5 the bank-in\'s proof is on the receipt it was paid on', oHtml.includes('second-cheque.png'));

  console.log('\nD. Paid ahead of the notes');
  const dr = await payments.recordDepositReceipt({ organizationId: orgId, tenantId: tenant.id, leaseId: L2.id, amount: '500', receivedDate: new Date('2025-10-02') });
  await payments.approve({ organizationId: orgId, receiptId: dr.id });
  const d = await documents.receiptContext(orgId, dr.id);
  ck('D1 held for its lease, addressed to that lease\'s premises', d.advance && d.lease.reference === 'ZZ-RCD-L2' && d.property.addressLines[0] === 'C, ZZ Receipt Plaza', JSON.stringify([d.advance, d.property.addressLines]));
  ck('D2 headed as the lease\'s notes would be today — it has none frozen', d.org.name === 'ZZ Receipt Org', d.org.name);
  const dHtml = (await documents.receiptHtml(orgId, dr.id)).html;
  ck('D3 no method, so no remark and no reference line', d.receipt.method === null && d.receipt.remark === null && !dHtml.includes('Remarks') && !dHtml.includes('padding-left:12mm'));
  ck('D4 its page says so', (await documents.receiptHtml(orgId, dr.id)).html.includes('Being payment received in advance for Lease ZZ-RCD-L2'));

  console.log('\nP. Only an approved payment has a receipt');
  const n3 = await issue('2025-10', '2025-10-01');
  const pending = await payments.submitReceipt({ organizationId: orgId, tenantId: tenant.id, invoiceId: n3.id, amount: '100' });
  ck('P1 a payment still waiting is refused', (await refused(documents.receiptContext(orgId, pending.id))) === 'A receipt is issued once the payment is approved');
  await payments.reject({ organizationId: orgId, receiptId: pending.id, reason: 'not received' });
  ck('P2 so is one refused', (await refused(documents.receiptContext(orgId, pending.id))) === 'A receipt is issued once the payment is approved');
  ck('P3 another organisation\'s receipt is not there', (await refused(documents.receiptContext('zz-no-such-org', rA.id))) === 'Receipt not found');

  console.log('\nB. A payment that bounced');
  await payments.bounce({ organizationId: orgId, receiptId: rO.id });
  const ob = await documents.receiptContext(orgId, rO.id);
  ck('B1 keeps its receipt, stamped DISHONOURED', ob.receipt.dishonoured && (await documents.receiptHtml(orgId, rO.id)).html.includes('DISHONOURED'));
  ck('B2 its excess bounced with it and is still named', ob.actual === '4000.00' && ob.excess.length === 1, JSON.stringify(ob.excess));
  ck('B3 the one that stands is not stamped', !(await documents.receiptContext(orgId, rA.id)).receipt.dishonoured);

  console.log('\nT. The tenant\'s portal, and the template');
  const login = await prisma.user.create({ data: { email: 'zz-rcd-tenant@rms.local', name: 'ZZ RCD', passwordHash: 'x', tenantId: tenant.id } });
  const portal = portalRouter.createCaller({
    prisma, organizationId: orgId,
    user: { id: login.id, email: 'zz', name: 'ZZ', tenantId: tenant.id, mustChangePassword: false, permissions: [], roles: [] },
  } as unknown as Context);
  const advances = await portal.advanceReceipts();
  ck('T1 the deposit receipts paid ahead — not the overpaid part, which is on its payment\'s receipt', JSON.stringify(advances.map((r) => [r.number, r.status, r.leaseRef, r.amount])) ===
    JSON.stringify([[dr.number, 'APPROVED', 'ZZ-RCD-L2', '500.00']]), JSON.stringify(advances));
  const paidRow = (await portal.invoice({ id: n2.id })).receipts.find((r) => r.id === rO.id);
  ck('T2 the note\'s payment row: all that was paid, and the part held in advance', paidRow?.amount === '4000.00' && paidRow.excess === '888.00', JSON.stringify(paidRow));
  const tpl = await documents.template(orgId, 'RECEIPT');
  ck('T3 a receipt template is there from the first print, the shipped one', tpl.name === 'Receipt' && tpl.body === DEFAULT_TEMPLATES.RECEIPT.body);
  const broken = (await documents.receiptHtml(orgId, rA.id, '{{#each}')).html;
  ck('T4 a broken template shows its fault on the page', broken.includes('Template error'));
}

async function purge() {
  await prisma.user.deleteMany({ where: { email: 'zz-rcd-tenant@rms.local' } });
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (org) {
    const where = { organizationId: org.id };
    for (const a of await prisma.attachment.findMany({ where, select: { storageKey: true } })) await storage.remove(a.storageKey);
    await prisma.attachment.deleteMany({ where });
    const entries = (await prisma.journalEntry.findMany({ where, select: { id: true } })).map((e) => e.id);
    await prisma.journalLine.deleteMany({ where: { entryId: { in: entries } } });
    await prisma.journalEntry.updateMany({ where: { id: { in: entries } }, data: { reversesId: null } });
    await prisma.journalEntry.deleteMany({ where: { id: { in: entries } } });
    const rcpIds = (await prisma.receipt.findMany({ where, select: { id: true } })).map((r) => r.id);
    await prisma.receiptAllocationItem.deleteMany({ where: { allocation: { receiptId: { in: rcpIds } } } });
    await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rcpIds } } });
    await prisma.receipt.updateMany({ where: { id: { in: rcpIds } }, data: { sourceReceiptId: null } });
    await prisma.receipt.deleteMany({ where: { id: { in: rcpIds } } });
    const depIds = (await prisma.deposit.findMany({ where, select: { id: true } })).map((x) => x.id);
    await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
    await prisma.deposit.deleteMany({ where });
    const invIds = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    const leaseIds = (await prisma.lease.findMany({ where, select: { id: true } })).map((l) => l.id);
    await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
    const props = (await prisma.property.findMany({ where, select: { id: true } })).map((p) => p.id);
    await prisma.unit.deleteMany({ where: { propertyId: { in: props } } });
    await prisma.property.deleteMany({ where: { id: { in: props } } });
    await prisma.tenant.deleteMany({ where }); // its code goes with it
    await prisma.landlord.deleteMany({ where });
    await prisma.chargeType.deleteMany({ where });
    await prisma.glAccount.deleteMany({ where });
    await prisma.numberSequence.deleteMany({ where });
    await prisma.documentTemplate.deleteMany({ where });
    await prisma.organization.delete({ where: { id: org.id } });
  }
  await prisma.settlementMethod.deleteMany({ where: { code: METHOD_CODE } });
  for (const key of savedKeys.splice(0)) await storage.remove(key);
}

async function cleanup() {
  try { await purge(); 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); });
