/**
 * Functional smoke: whose letterhead a debit note is printed under.
 *
 * The group holds its buildings through ~20 limited companies, and the owner's
 * answer to "whose name is on the note" was "it depends": some buildings bill
 * under the owning company, the rest under the management company the system
 * runs as. Until now every note printed the organisation, full stop.
 *
 * The behaviour that matters and is easy to lose is the same one the payee has:
 * what a note SAID is frozen when it is issued. Re-printing last year's note
 * must show last year's company and last year's address.
 *
 * What this proves against the real billing service and the real renderer:
 *   · a building set to its owning company prints that company on a DRAFT;
 *   · issuing freezes it — name, address, telephone;
 *   · the company then moving office does NOT move the issued note, and DOES
 *     move the next one;
 *   · a building left on the organisation prints exactly what it printed
 *     before this existed — checked against a note issued before it, which the
 *     smoke constructs (an issued note with no snapshot);
 *   · a note issued before this existed keeps printing the ORGANISATION even
 *     after its building is switched to a landlord letterhead — the one case
 *     where "print the current setting" would rewrite history;
 *   · a company with no address cannot be chosen, and its address cannot be
 *     taken away while a building prints under it — an ARCHIVED building counts,
 *     because restoring it makes that heading live again;
 *   · the debit-note screen's readout agrees with the paper, and calls a
 *     pre-change note frozen rather than offering to print something else;
 *   · the payee bank account still freezes exactly as it did;
 *   · a property in another country prints its landlord's contact there, the
 *     company's own where that is blank or there is none, frozen at issue;
 *   · the tenant's address, phone and email print as its record says to, on a
 *     template saved before they did too;
 *   · a note not yet issued pays into whatever account its lease does now.
 *
 * Assertions are on the render INPUT — `documents.invoiceHtml`, the byte-exact
 * HTML handed to Chromium — plus one real `invoicePdf` call to prove the whole
 * path runs. Text cannot be read back out of the PDF: Chromium subsets its
 * fonts, so the strings inside the content stream are glyph ids, not words. The
 * PDF check is skipped (loudly) when no browser is installed, which is what
 * PdfService.rendererStatus() exists to answer.
 *
 * Standalone, self-cleaning: its own ZZ organisation, purged at each end.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/letterhead-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Prisma } from '@prisma/client';
import { StorageService } from '../src/attachments/storage.service';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { DocumentService } from '../src/documents/document.service';
import { PdfService } from '../src/documents/pdf.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { invoicesRouter } from '../src/trpc/routers/invoices.router';
import { landlordsRouter } from '../src/trpc/routers/landlords.router';
import { leasesRouter } from '../src/trpc/routers/leases.router';
import { propertiesRouter } from '../src/trpc/routers/properties.router';
import type { AuthUser } from '../src/trpc/auth-user';
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 config = new ConfigService();
const pdf = new PdfService(config);
const documents = new DocumentService(prisma, new StorageService(config), pdf);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const PFX = 'ZZ-LH';
const ORG_CODE = `${PFX}-ORG`;
const ORG_NAME = 'ZZ Well Faith Management Limited';
const ORG_ADDRESS = 'Room 1201, ZZ Commercial Building, 12 Queen Street, Central, Hong Kong';
const OWNER_NAME = 'ZZ Alpha Investment Company Limited';
const OWNER_ADDRESS = 'Flat A, 8/F, ZZ Alpha House, 88 Nathan Road, Kowloon';

const staff: AuthUser = {
  id: 'zz-lh-staff', email: 'zz-lh@rms.local', name: 'ZZ LH Staff', tenantId: null, mustChangePassword: false,
  roles: ['ADMIN'],
  permissions: ['property.read', 'property.create', 'property.update', 'property.delete', 'landlord.read', 'landlord.create', 'landlord.update', 'invoice.read', 'lease.update'],
};
const ctxOf = (orgId: string): Context => ({ prisma, user: staff, organizationId: orgId } as unknown as Context);

/** The letterhead block as the template renders it: the name line and the
 *  address line, straight out of the HTML the renderer is handed. */
function headingOf(html: string): { name: string; sub: string } {
  const name = /<div class="letterhead">([\s\S]*?)<\/div>/.exec(html)?.[1]?.trim() ?? '';
  const sub = /<div class="subhead">([\s\S]*?)<\/div>/.exec(html)?.[1]?.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() ?? '';
  return { name, sub };
}

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const invoices = await prisma.invoice.findMany({ where: { organizationId: org.id }, select: { id: true } });
  const ids = invoices.map((i) => i.id);
  if (ids.length) {
    const entries = await prisma.journalEntry.findMany({
      where: { OR: [{ sourceId: { in: ids } }, { lines: { some: { invoiceId: { in: ids } } } }] },
      select: { id: true },
    });
    const eids = entries.map((e) => e.id);
    if (eids.length) {
      await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
      await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
    }
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: ids } } });
    await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
  }
  const leases = await prisma.lease.findMany({ where: { organizationId: org.id }, select: { id: true } });
  const leaseIds = leases.map((l) => l.id);
  if (leaseIds.length) {
    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: { organizationId: org.id }, select: { id: true } });
  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.landlord.deleteMany({ where: { organizationId: org.id } });
  await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
  await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
  await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
  await prisma.bankAccount.deleteMany({ where: { organizationId: org.id } });
  await prisma.numberSequence.deleteMany({ where: { organizationId: org.id } });
  await prisma.documentTemplate.deleteMany({ where: { organizationId: org.id } });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function main() {
  await purge();
  const org = await prisma.organization.create({
    data: { code: ORG_CODE, name: ORG_NAME, nameZh: 'ZZ 威信管理有限公司', address: ORG_ADDRESS, tel: '2345 6789', email: 'zz@rms.local' },
  });
  const orgId = org.id;
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZZLH-', padding: 5 } });
  const ar = await prisma.glAccount.create({ data: { organizationId: orgId, code: '1100', name: 'Accounts Receivable', type: 'ASSET', role: 'RECEIVABLE' } });
  const income = await prisma.glAccount.create({ data: { organizationId: orgId, code: '4000', name: 'Rental Income', type: 'INCOME' } });
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: income.id } });
  await prisma.bankAccount.create({
    // Deliberately a different name from both companies: the cheque payee is
    // the bank account, and must not follow the letterhead anywhere.
    data: { organizationId: orgId, name: 'ZZ LH Main', bankName: 'ZZ Bank HK', accountName: 'ZZ Well Faith Collections Limited', accountNumber: '111-222-333', isCollectionAgent: true, isActive: true },
  });
  const props = propertiesRouter.createCaller(ctxOf(orgId));
  const landlords = landlordsRouter.createCaller(ctxOf(orgId));

  const owner = await landlords.create({ code: 'ZA', name: OWNER_NAME, nameZh: 'ZZ 阿爾法投資有限公司', address: OWNER_ADDRESS, tel: '2111 2222', isActive: true, sortOrder: 0 });
  const homeless = await landlords.create({ code: 'ZN', name: 'ZZ Nomad Holdings Limited', isActive: true, sortOrder: 1 });

  const ownedId = (await props.create({ name: `${PFX} Alpha Tower`, address: '88 Nathan Road, Kowloon', landlordId: owner.id, letterheadSource: 'LANDLORD' })).id;
  const managedId = (await props.create({ name: `${PFX} Beta Court`, address: '9 Queen Street, Central', landlordId: owner.id })).id;
  for (const id of [ownedId, managedId]) await prisma.unit.create({ data: { propertyId: id, name: 'ZZ 1/F' } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant`, attention: 'Mr ZZ Chan' } });

  const mkLease = async (suffix: string, propertyId: string, start: string) => {
    const unit = await prisma.unit.findFirstOrThrow({ where: { propertyId } });
    return prisma.lease.create({
      data: {
        organizationId: orgId, reference: `${PFX}-${suffix}`, tenantId: tenant.id, status: 'ACTIVE',
        currency: 'HKD', startDate: new Date(start), endDate: new Date('2100-01-01'), depositMonths: 0,
        units: { create: { unitId: unit.id } },
        chargeRules: { create: [{ chargeTypeId: rent.id, amount: '12000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
      },
    });
  };
  const raise = async (leaseId: string, period: string) => billing.generateDraft({ organizationId: orgId, leaseId, period });
  const headingFor = async (invoiceId: string) => headingOf((await documents.invoiceHtml(orgId, invoiceId)).html);

  const ownedLease = await mkLease('OWNED', ownedId, '2024-01-01');
  const managedLease = await mkLease('MANAGED', managedId, '2024-01-01');

  console.log('A. A building billed under its owning company');
  const draftO = await raise(ownedLease.id, '2024-01');
  const draftHeading = await headingFor(draftO.id);
  ck('A1 a DRAFT prints the owning company', draftHeading.name === OWNER_NAME, `got "${draftHeading.name}"`);
  ck('A2 with that company’s address', draftHeading.sub.includes(OWNER_ADDRESS), `got "${draftHeading.sub}"`);
  ck('A3 and its telephone', draftHeading.sub.includes('2111 2222'), `got "${draftHeading.sub}"`);
  ck('A4 not the management company', !draftHeading.name.includes(ORG_NAME) && !draftHeading.sub.includes(ORG_ADDRESS));
  ck('A5 a draft has nothing frozen yet',
    (await prisma.invoice.findUniqueOrThrow({ where: { id: draftO.id }, select: { letterheadSnapshot: true } })).letterheadSnapshot === null);

  console.log('\nB. Issuing freezes it');
  await billing.issue({ organizationId: orgId, invoiceId: draftO.id });
  const frozen = (await prisma.invoice.findUniqueOrThrow({ where: { id: draftO.id }, select: { letterheadSnapshot: true } })).letterheadSnapshot as Record<string, unknown>;
  ck('B1 the note carries the company it was issued under', frozen?.name === OWNER_NAME, JSON.stringify(frozen));
  ck('B2 with the address it had that day', frozen?.address === OWNER_ADDRESS, JSON.stringify(frozen));
  const issuedHeading = await headingFor(draftO.id);
  ck('B3 and prints the same thing', issuedHeading.name === OWNER_NAME && issuedHeading.sub.includes(OWNER_ADDRESS));

  console.log('\nC. The company moves office');
  const MOVED = 'Unit 30, 30/F, ZZ Harbour Centre, 1 Harbour Road, Wan Chai';
  await landlords.update({ id: owner.id, code: 'ZA', name: OWNER_NAME, address: MOVED, tel: '2111 2222', isActive: true, sortOrder: 0 });
  const stillOld = await headingFor(draftO.id);
  ck('C1 the issued note keeps the address it was issued with', stillOld.sub.includes(OWNER_ADDRESS) && !stillOld.sub.includes(MOVED), `got "${stillOld.sub}"`);
  const draftLater = await raise(ownedLease.id, '2024-02');
  ck('C2 a new draft picks up the new address', (await headingFor(draftLater.id)).sub.includes(MOVED));
  await billing.issue({ organizationId: orgId, invoiceId: draftLater.id });
  ck('C3 and the note issued after the move keeps THAT one', (await headingFor(draftLater.id)).sub.includes(MOVED));
  ck('C4 while the older note is still unchanged', (await headingFor(draftO.id)).sub.includes(OWNER_ADDRESS));

  console.log('\nD. A building left on the organisation prints what it always printed');
  // The comparison case: a note issued BEFORE this feature existed has no
  // snapshot at all. Built by clearing the column, which is exactly the state
  // every note already in the database is in.
  const legacy = await raise(managedLease.id, '2024-01');
  await billing.issue({ organizationId: orgId, invoiceId: legacy.id });
  await prisma.invoice.update({ where: { id: legacy.id }, data: { letterheadSnapshot: Prisma.DbNull } });
  const legacyHeading = await headingFor(legacy.id);
  ck('D1 a note issued before this change prints the organisation', legacyHeading.name === ORG_NAME, `got "${legacyHeading.name}"`);
  ck('D2 with the organisation’s address', legacyHeading.sub.includes(ORG_ADDRESS), `got "${legacyHeading.sub}"`);
  const fresh = await raise(managedLease.id, '2024-02');
  await billing.issue({ organizationId: orgId, invoiceId: fresh.id });
  const freshHeading = await headingFor(fresh.id);
  ck('D3 a note issued today prints exactly the same heading', freshHeading.name === legacyHeading.name && freshHeading.sub === legacyHeading.sub,
    `"${freshHeading.name}/${freshHeading.sub}" vs "${legacyHeading.name}/${legacyHeading.sub}"`);

  console.log('\nE. Switching a building later does not rewrite its old notes');
  // The trap: an old note has no snapshot, so "print the current setting" would
  // silently reissue it under a company that never billed that tenant.
  await props.update({ id: managedId, name: `${PFX} Beta Court`, landlordId: owner.id, letterheadSource: 'LANDLORD' });
  const afterSwitch = await headingFor(legacy.id);
  ck('E1 the pre-change note still prints the organisation', afterSwitch.name === ORG_NAME, `got "${afterSwitch.name}"`);
  ck('E2 and still its address', afterSwitch.sub === legacyHeading.sub, `got "${afterSwitch.sub}"`);
  ck('E3 the note issued after this change also keeps what it froze', (await headingFor(fresh.id)).name === ORG_NAME);
  const nextDraft = await raise(managedLease.id, '2024-03');
  ck('E4 but the next draft prints the owning company', (await headingFor(nextDraft.id)).name === OWNER_NAME);

  console.log('\nF. A company with no address is not a letterhead');
  const noAddress = await refused(() => props.update({ id: ownedId, name: `${PFX} Alpha Tower`, landlordId: homeless.id, letterheadSource: 'LANDLORD' }));
  ck('F1 a company with no address cannot be chosen', noAddress.includes('no address on file'), `got "${noAddress}"`);
  const noCompany = await refused(() => props.update({ id: ownedId, name: `${PFX} Alpha Tower`, landlordId: null, letterheadSource: 'LANDLORD' }));
  ck('F2 nor can the setting be made without a company at all', noCompany.includes('Choose the owning company'), `got "${noCompany}"`);
  ck('F3 the refusal changed nothing', (await props.get({ id: ownedId })).landlordId === owner.id);
  const takeAway = await refused(() => landlords.update({ id: owner.id, code: 'ZA', name: OWNER_NAME, address: '', tel: '2111 2222', isActive: true, sortOrder: 0 }));
  ck('F4 the address cannot be taken away while buildings print under it', takeAway.includes('needs an address'), `got "${takeAway}"`);
  ck('F5 …and it still has it', (await landlords.get({ id: owner.id })).address === MOVED);
  const okOnOrg = await refused(() => landlords.update({ id: homeless.id, code: 'ZN', name: 'ZZ Nomad Holdings Limited', address: '', isActive: true, sortOrder: 1 }));
  ck('F6 a company nothing prints under may stay address-less', okOnOrg === '', `got "${okOnOrg}"`);

  // An ARCHIVED building still names its company. Counting only live ones would
  // leave the back door open: archive the building, clear the address, restore
  // it — and the building is live again with a letterhead that cannot print,
  // so the next note silently heads back to the management company and FREEZES
  // it, while the Properties list still shows the owning company.
  const sold = await landlords.create({ code: 'ZS', name: 'ZZ Sunset Holdings Limited', address: 'Shop 3, ZZ Sunset Mansion, 3 Sai Yeung Choi Street', isActive: true, sortOrder: 2 });
  const soldId = (await props.create({ name: `${PFX} Sunset Court`, address: '3 Sai Yeung Choi Street', landlordId: sold.id, letterheadSource: 'LANDLORD' })).id;
  await props.archive({ id: soldId });
  const archivedStillCounts = await refused(() => landlords.update({ id: sold.id, code: 'ZS', name: 'ZZ Sunset Holdings Limited', address: '', isActive: true, sortOrder: 2 }));
  ck('F7 an archived building still protects its company’s address', archivedStillCounts.includes('needs an address'), `got "${archivedStillCounts}"`);
  ck('F8 …so the address survives', (await landlords.get({ id: sold.id })).address !== null && (await landlords.get({ id: sold.id })).address !== '');
  await props.restore({ id: soldId });
  const resaved = await refused(() => props.update({ id: soldId, name: `${PFX} Sunset Court Renamed`, landlordId: sold.id, letterheadSource: 'LANDLORD' }));
  ck('F9 so the restored building is still saveable, not stuck on a heading it cannot print', resaved === '', `got "${resaved}"`);

  console.log('\nG. What the debit-note screen says matches what prints');
  // The screen reads the same helper the renderer does, so the name always
  // agrees. `frozen` is the other half of that line — it is what tells the
  // office whether this note can still move — and it has to mean exactly what
  // the helper means by immutable, INCLUDING the pre-change note, which has no
  // snapshot and is pinned to the organisation all the same.
  const invoices = invoicesRouter.createCaller(ctxOf(orgId));
  const legacyRead = (await invoices.get({ id: legacy.id })).letterhead;
  ck('G1 a note issued before this change reads as frozen, not as a draft', legacyRead.frozen === true, JSON.stringify(legacyRead));
  ck('G2 …and names the organisation, which is what it prints', legacyRead.name === ORG_NAME && legacyRead.name === (await headingFor(legacy.id)).name, JSON.stringify(legacyRead));
  const snapRead = (await invoices.get({ id: draftO.id })).letterhead;
  ck('G3 a note issued with a snapshot reads as frozen too', snapRead.frozen === true && snapRead.name === OWNER_NAME, JSON.stringify(snapRead));
  const draftRead = (await invoices.get({ id: nextDraft.id })).letterhead;
  ck('G4 a DRAFT is the only thing that reads as not frozen', draftRead.frozen === false && draftRead.name === OWNER_NAME, JSON.stringify(draftRead));

  console.log('\nH. The payee is untouched by all this');
  const payee = (await prisma.invoice.findUniqueOrThrow({ where: { id: draftO.id }, select: { payeeSnapshot: true } })).payeeSnapshot as Record<string, unknown>;
  ck('H1 issuing still freezes the bank account', payee?.accountNumber === '111-222-333', JSON.stringify(payee));
  const html = (await documents.invoiceHtml(orgId, draftO.id)).html;
  ck('H2 and the note still says to pay it', html.includes('111-222-333') && html.includes('ZZ Bank HK'));
  ck('H3 the cheque payee is the bank account’s name, not the company at the top of the page',
    html.includes('<span class="payee">ZZ Well Faith Collections Limited</span>') && headingOf(html).name === OWNER_NAME,
    `heading "${headingOf(html).name}"`);
  ck('H4 a draft still has no payee frozen',
    (await prisma.invoice.findUniqueOrThrow({ where: { id: nextDraft.id }, select: { payeeSnapshot: true } })).payeeSnapshot === null);

  console.log('\nI. The real PDF');
  const renderer = pdf.rendererStatus();
  if (!renderer.ok) {
    console.log(`  — skipped: no PDF renderer here (${renderer.source}: ${renderer.detail ?? ''})`);
  } else {
    const bytes = await documents.invoicePdf(orgId, draftO.id);
    ck('I1 the issued note renders to a real PDF', bytes.subarray(0, 5).toString() === '%PDF-' && bytes.length > 1000, `${bytes.length} bytes`);
  }

  console.log('\nJ. A property abroad prints its landlord’s contact there');
  // The colleagues in Singapore deal with the tenants there, so that is the
  // phone and email their notes print; the company's own stay on the rest.
  const country = (code: string, nameEn: string) => prisma.referenceValue.create({ data: { organizationId: orgId, domain: 'COUNTRY', code, nameEn } });
  const hk = await country('HK', 'Hong Kong');
  const sg = await country('SG', 'Singapore');
  const ownerAs = (contacts: { countryId: string; tel?: string | null; email?: string | null }[]) =>
    landlords.update({ id: owner.id, code: 'ZA', name: OWNER_NAME, address: MOVED, tel: '2111 2222', email: 'hk@zz.local', contacts, isActive: true, sortOrder: 0 });
  await ownerAs([{ countryId: sg.id, tel: '+65 6111 2222', email: 'sg@zz.local' }]);
  const sgId = (await props.create({ name: `${PFX} Bedok Point`, address: '218 Bedok North Street 1, Singapore', landlordId: owner.id, letterheadSource: 'LANDLORD', countryId: sg.id })).id;
  await prisma.unit.create({ data: { propertyId: sgId, name: 'ZZ #01-19' } });
  const sgLease = await mkLease('SG', sgId, '2024-01-01');
  const sgDraft = await raise(sgLease.id, '2024-01');
  const sgHead = (await headingFor(sgDraft.id)).sub;
  ck('J1 a property in Singapore prints the Singapore phone and email', sgHead.includes('+65 6111 2222') && sgHead.includes('sg@zz.local') && !sgHead.includes('2111 2222'), `got "${sgHead}"`);
  ck('J2 under the same company, name and address', (await headingFor(sgDraft.id)).name === OWNER_NAME && sgHead.includes(MOVED));
  await props.update({ id: ownedId, name: `${PFX} Alpha Tower`, landlordId: owner.id, letterheadSource: 'LANDLORD', countryId: hk.id });
  const hkHead = (await headingFor((await raise(ownedLease.id, '2024-04')).id)).sub;
  ck('J3 a property in a country with no contact of its own prints the company’s', hkHead.includes('2111 2222') && hkHead.includes('hk@zz.local'), `got "${hkHead}"`);
  await ownerAs([{ countryId: sg.id, tel: '+65 6111 2222', email: '' }]);
  const halfHead = (await headingFor(sgDraft.id)).sub;
  ck('J4 a blank field there falls back to the company’s own', halfHead.includes('+65 6111 2222') && halfHead.includes('hk@zz.local'), `got "${halfHead}"`);
  await billing.issue({ organizationId: orgId, invoiceId: sgDraft.id });
  await ownerAs([{ countryId: sg.id, tel: '+65 6999 0000', email: 'sg@zz.local' }]);
  const issuedHead = (await headingFor(sgDraft.id)).sub;
  ck('J5 an issued note keeps the contact it was issued with', issuedHead.includes('+65 6111 2222') && !issuedHead.includes('+65 6999 0000'), `got "${issuedHead}"`);
  ck('J6 one contact per country', (await refused(() => ownerAs([{ countryId: sg.id, tel: '1' }, { countryId: sg.id, tel: '2' }]))) === 'Each country can have only one contact');
  ck('J7 a country must be one of the list', (await refused(() => props.update({ id: sgId, name: `${PFX} Bedok Point`, countryId: rent.id }))) === 'Country not found');
  ck('J8 a save that does not mention the contacts leaves them',
    (await landlords.update({ id: owner.id, code: 'ZA', name: OWNER_NAME, address: MOVED, tel: '2111 2222', isActive: true, sortOrder: 0 }).then(() => landlords.get({ id: owner.id }))).contacts.length === 1);

  console.log('\nK. What of the tenant is printed');
  const sgNext = await raise(sgLease.id, '2024-02');
  await prisma.tenant.update({ where: { id: tenant.id }, data: { address: 'Blk 321 ZZ Road\nSingapore 238866', phone: '+65 6278 6988', email: 'billing@zz-tenant.local' } });
  const tenantHtml = async () => (await documents.invoiceHtml(orgId, sgNext.id)).html;
  let th = await tenantHtml();
  ck('K1 the tenant’s address, phone and email, once filled', th.includes('Blk 321 ZZ Road') && th.includes('+65 6278 6988') && th.includes('Email :</td><td>billing@zz-tenant.local'));
  await prisma.tenant.update({ where: { id: tenant.id }, data: { printEmail: false, printAddress: false } });
  th = await tenantHtml();
  ck('K2 untick one and it is not printed — the rest still are', !th.includes('billing@zz-tenant.local') && !th.includes('Blk 321 ZZ Road') && th.includes('+65 6278 6988'));
  await prisma.tenant.update({ where: { id: tenant.id }, data: { printEmail: true, printAddress: true } });
  // A template saved before this change: no address under the name, no email row.
  const stored = await documents.template(orgId, 'INVOICE');
  await prisma.documentTemplate.update({
    where: { id: stored.id },
    data: {
      body: stored.body
        .replace('{{#if tenant.address}}<div style="white-space:pre-line">{{tenant.address}}</div>{{/if}}', '')
        .replace('{{#if tenant.email}}<tr><td>Email :</td><td>{{tenant.email}}</td></tr>{{/if}}', ''),
    },
  });
  th = await tenantHtml();
  ck('K3 a template saved before this change prints them too', th.includes('Blk 321 ZZ Road') && th.includes('billing@zz-tenant.local'));

  console.log('\nL. A note not yet issued pays into the lease’s account as it is now');
  const sgBank = await prisma.bankAccount.create({
    data: { organizationId: orgId, name: 'ZZ LH SG', bankName: 'ZZ UOB', accountName: 'ZZ Lucky Forever (S) Pte Ltd', accountNumber: '450-304-894-3', isActive: true },
  });
  const leases = leasesRouter.createCaller(ctxOf(orgId));
  const sgUnit = await prisma.unit.findFirstOrThrow({ where: { propertyId: sgId } });
  const editLease = (bankAccountId: string | null) =>
    leases.update({
      id: sgLease.id, reference: sgLease.reference, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD', startDate: '2024-01-01', endDate: '2100-01-01',
      bankAccountId, unitIds: [sgUnit.id],
      chargeRules: [{ chargeTypeId: rent.id, amount: '12000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false }],
    });
  ck('L1 before: the draft pays into the collection account', (await tenantHtml()).includes('111-222-333'));
  await editLease(sgBank.id);
  const after = await tenantHtml();
  ck('L2 the lease’s account changes, and the draft follows — no void, no rebuild', after.includes('450-304-894-3') && !after.includes('111-222-333'));
  ck('L3 the issued note keeps the account it was issued with', (await documents.invoiceHtml(orgId, sgDraft.id)).html.includes('111-222-333'));
}

main()
  .catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); })
  .finally(async () => {
    await purge().catch((e) => console.log('cleanup warn', e instanceof Error ? e.message : e));
    await pdf.onModuleDestroy().catch(() => undefined);
    await prisma.$disconnect();
    console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} passed, ${fail} failed`);
    process.exit(fail === 0 ? 0 : 1);
  });
