/**
 * Functional smoke: a property is one purchase, and a lease takes its units
 * from any purchase of one building.
 *
 * The office registers a property each time it buys units — the same building
 * bought three times is three properties under one building name — and one
 * tenancy may let units from all three. So a lease names no property of its
 * own: its company, its letterhead, its standard charges and its address are
 * read through its units.
 *
 * What this proves against the real routers, billing service and renderer:
 *   · a purchase's number is drawn from the PROPERTY sequence — company, year
 *     and month of completion, a count per company per month — once the
 *     landlord and completion date are known, and never redrawn; a typed one is
 *     taken as typed, and a duplicate refused;
 *   · the sale, the purchase price and the land lease read back; a sale before
 *     the purchase is refused;
 *   · one building is the properties sharing a name, however it was spaced;
 *   · a lease takes units of three purchases, and is refused a unit of another
 *     building, of another company, under another letterhead, or of a sold
 *     purchase — while the units it already holds stay saveable once sold;
 *   · a charge following the standard bills each unit at its own purchase's
 *     figure, not another purchase's;
 *   · the debit note is numbered under the units' company, printed with the
 *     building's name, and the rent roll names the building.
 *
 * Standalone, self-cleaning: its own ZZ organisation, purged at each end.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/building-purchase-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
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 { ReportsService } from '../src/reports/reports.service';
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 billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
const config = new ConfigService();
const pdf = new PdfService(config);
const documents = new DocumentService(prisma, new StorageService(config), pdf);
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}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const ORG_CODE = 'ZZ-BP-ORG';
const BUILDING = 'Sino ZZ Plaza';

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

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.standardCharge.deleteMany({ where: { organizationId: org.id } });
  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.organization.delete({ where: { id: org.id } });
}

async function main() {
  await purge();
  const org = await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Building Purchase Org', address: '1 ZZ Road' } });
  const orgId = org.id;
  await prisma.numberSequence.createMany({
    data: [
      { organizationId: orgId, docType: 'PROPERTY', prefix: 'P-', parts: 'SYMBOL,COMPANY,YEAR,MONTH,SERIAL', padding: 2, resetPeriod: 'MONTHLY' },
      { organizationId: orgId, docType: 'LEASE', prefix: 'ZZBPL-', parts: 'SYMBOL,COMPANY,SERIAL', padding: 3 },
      { organizationId: orgId, docType: 'INVOICE', prefix: 'ZZBP-', parts: 'SYMBOL,COMPANY,SERIAL', padding: 5 },
    ],
  });
  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 } });
  const mgmt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'MGMT', nameEn: 'Management Fee', category: 'RECURRING', glAccountId: income.id } });
  await prisma.bankAccount.create({ data: { organizationId: orgId, name: 'ZZ BP Main', bankName: 'ZZ Bank', accountName: 'ZZ BP', accountNumber: '1', isCollectionAgent: true, isActive: true } });

  const properties = propertiesRouter.createCaller(ctxOf(orgId));
  const leases = leasesRouter.createCaller(ctxOf(orgId));
  const landlords = landlordsRouter.createCaller(ctxOf(orgId));
  const zw = await landlords.create({ code: 'ZW', name: 'ZZ Well Faith Limited', address: '2 ZZ Road', isActive: true, sortOrder: 0 });
  const zx = await landlords.create({ code: 'ZX', name: 'ZZ Other Holdings Limited', isActive: true, sortOrder: 1 });
  const codeOf = async (id: string) => (await properties.get({ id })).code;
  const unitOf = async (id: string, name: string) => (await properties.get({ id })).units.find((u) => u.name === name)!.id;

  console.log('A. Each purchase, numbered and recorded');
  const p1 = await properties.create({
    name: BUILDING, address: '6/F, Sino ZZ Plaza, 9 ZZ Road', landlordId: zw.id, completionDate: '2024-03-26', purchasePrice: '12800000',
    landLeaseTerm: '99 years', landLeaseCommencement: '1898-07-01', units: [{ name: '611' }, { name: '612' }],
  });
  ck('A1 the first purchase is numbered by company, year and month of completion', (await codeOf(p1.id)) === 'P-ZW240301', `got ${await codeOf(p1.id)}`);
  const p2 = await properties.create({ name: '  sino zz   plaza ', address: '6/F, Sino ZZ Plaza, 9 ZZ Road', landlordId: zw.id, completionDate: '2024-03-05', units: [{ name: '621' }] });
  ck('A2 a second that month is the second of the month', (await codeOf(p2.id)) === 'P-ZW240302', `got ${await codeOf(p2.id)}`);
  const p3 = await properties.create({ name: BUILDING, address: '6/F, Sino ZZ Plaza, 9 ZZ Road', landlordId: zw.id, completionDate: '2025-06-10', units: [{ name: '631' }] });
  ck('A3 a new month starts again at 01', (await codeOf(p3.id)) === 'P-ZW250601', `got ${await codeOf(p3.id)}`);
  const p4 = await properties.create({ name: BUILDING, completionDate: '2025-06-20', units: [{ name: '641' }] });
  ck('A4 without a landlord there is no number yet', (await codeOf(p4.id)) === null);
  await properties.update({ id: p4.id, name: BUILDING, landlordId: zw.id });
  ck('A5 naming the landlord draws it then, under that company', (await codeOf(p4.id)) === 'P-ZW250602', `got ${await codeOf(p4.id)}`);
  await properties.update({ id: p1.id, name: BUILDING, landlordId: zw.id, completionDate: '2024-04-01' });
  ck('A6 a number once drawn stays when the date moves', (await codeOf(p1.id)) === 'P-ZW240301', `got ${await codeOf(p1.id)}`);
  const p5 = await properties.create({ name: BUILDING, landlordId: zx.id, completionDate: '2024-03-15', units: [{ name: '651' }] });
  ck('A7 another company counts its own month', (await codeOf(p5.id)) === 'P-ZX240301', `got ${await codeOf(p5.id)}`);
  const other = await properties.create({ name: 'ZZ Other Tower', landlordId: zw.id, code: 'ZZ-TYPED-1', units: [{ name: 'T1' }] });
  ck('A8 a typed number is taken as typed', (await codeOf(other.id)) === 'ZZ-TYPED-1');
  const dupCode = await refused(() => properties.create({ name: 'ZZ Other Tower', code: 'ZZ-TYPED-1' }));
  ck('A9 and a typed number already used is refused', dupCode === 'Number ZZ-TYPED-1 is already used', `got "${dupCode}"`);
  const p1Got = await properties.get({ id: p1.id });
  ck('A10 the purchase and the land lease read back',
    p1Got.purchasePrice === '12800000.00' && p1Got.landLeaseTerm === '99 years' && p1Got.landLeaseCommencement === '1898-07-01' && p1Got.completionDate === '2024-04-01',
    JSON.stringify(p1Got));
  const early = await refused(() => properties.update({ id: p1.id, name: BUILDING, saleCompletionDate: '2024-01-01' }));
  ck('A11 a sale before the purchase is refused', early === 'A property cannot be sold before its purchase completed', `got "${early}"`);
  ck('A12 another purchase takes the building’s name as on file, however it was typed', (await properties.get({ id: p2.id })).name === BUILDING, (await properties.get({ id: p2.id })).name);
  const buildings = (await properties.formData()).buildings;
  ck('A13 the form offers the building once', buildings.filter((b) => b.toLowerCase() === BUILDING.toLowerCase()).length === 1, JSON.stringify(buildings));

  console.log('\nB. A lease across three purchases of one building');
  const form = await leases.formData();
  const building = form.buildings.find((b) => b.name.toLowerCase() === BUILDING.toLowerCase());
  ck('B1 the lease form offers one building with the units of every purchase',
    form.buildings.filter((b) => b.name.toLowerCase() === BUILDING.toLowerCase()).length === 1 && ['611', '612', '621', '631', '641', '651'].every((n) => building?.units.some((u) => u.name === n)),
    JSON.stringify(building?.units.map((u) => `${u.name}:${u.propertyCode}`)));
  const [u611, u612, u621, u631, u651, uT1] = await Promise.all([
    unitOf(p1.id, '611'), unitOf(p1.id, '612'), unitOf(p2.id, '621'), unitOf(p3.id, '631'), unitOf(p5.id, '651'), unitOf(other.id, 'T1'),
  ]);
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ BP Tenant' } });
  const terms = {
    tenantId: tenant.id, status: 'ACTIVE' as const, currency: 'HKD' as const, startDate: '2026-01-01', endDate: '2027-12-31', depositMonths: 0,
    chargeRules: [
      { chargeTypeId: rent.id, amount: '30000', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false },
      { chargeTypeId: mgmt.id, amount: '999', frequencyMonths: 1, timing: 'ADVANCE' as const, proration: 'FULL_MONTH' as const, firstInvoiceOnly: false, followsStandard: true },
    ],
  };
  const lease = await leases.create({ ...terms, unitIds: [u611, u621, u631] });
  const leaseRef = (await prisma.lease.findUniqueOrThrow({ where: { id: lease.id }, select: { reference: true } })).reference;
  ck('B2 the lease is saved, numbered under the units’ company', leaseRef === 'ZZBPL-ZW001', `got ${leaseRef}`);
  const otherCompany = await refused(() => leases.create({ ...terms, unitIds: [u611, u651] }));
  ck('B3 a unit of another company’s purchase is refused', otherCompany === 'All the units of a lease must belong to one landlord company', `got "${otherCompany}"`);
  const otherBuilding = await refused(() => leases.create({ ...terms, unitIds: [u611, uT1] }));
  ck('B4 a unit of another building is refused', otherBuilding === 'All the units of a lease must be in one building', `got "${otherBuilding}"`);
  const none = await refused(() => leases.create({ ...terms, unitIds: [] }));
  ck('B5 a lease with no unit is refused', none.includes('Choose at least one unit for the lease'), `got "${none}"`);
  await properties.update({ id: p3.id, name: BUILDING, landlordId: zw.id, letterheadSource: 'LANDLORD' });
  const heading = await refused(() => leases.update({ ...terms, id: lease.id, unitIds: [u611, u621, u631] }));
  ck('B6 purchases printed under different letterheads cannot share a lease', heading.startsWith("This lease's units are on properties printed under different letterheads"), `got "${heading}"`);
  await properties.update({ id: p3.id, name: BUILDING, landlordId: zw.id, letterheadSource: 'ORGANIZATION' });

  await properties.update({ id: p2.id, name: BUILDING, saleCompletionDate: '2026-06-30', salePrice: '15000000' });
  const p2Row = (await properties.list()).find((p) => p.id === p2.id);
  ck('B7 a sold purchase is listed as sold, with its price', p2Row?.saleCompletionDate != null && p2Row?.salePrice === '15000000.00', JSON.stringify(p2Row));
  const offered = (await leases.formData()).buildings.flatMap((b) => b.units).find((u) => u.id === u621);
  ck('B8 its units are no longer offered to a new lease', offered?.available === false);
  const sold = await refused(() => leases.create({ ...terms, unitIds: [u612, u621] }));
  ck('B9 and a new lease taking one is refused', sold === 'Unit 621 is on a property that has been sold or archived', `got "${sold}"`);
  const kept = await refused(() => leases.update({ ...terms, id: lease.id, unitIds: [u611, u621, u631] }));
  ck('B10 the lease already holding it still saves', kept === '', `got "${kept}"`);
  const counts = await properties.list();
  ck('B11 each purchase counts the lease on it', [p1.id, p2.id, p3.id].every((id) => counts.find((p) => p.id === id)?.leases === 1) && counts.find((p) => p.id === p4.id)?.leases === 0);
  const archiving = await refused(() => properties.archive({ id: p1.id }));
  ck('B12 a purchase a lease is on cannot be archived', archiving.startsWith('This property still has 1 lease(s)'), `got "${archiving}"`);
  ck('B13 the lease list names the building', (await leases.list()).find((l) => l.id === lease.id)?.propertyName === BUILDING);

  console.log('\nC. Billed through its units');
  // One purchase's own figure, a unit's own on another, a third purchase's own.
  await prisma.standardCharge.createMany({
    data: [
      { organizationId: orgId, propertyId: p1.id, unitId: null, chargeTypeId: mgmt.id, amount: '1000', effectiveFrom: new Date('2024-01-01') },
      { organizationId: orgId, propertyId: p2.id, unitId: u621, chargeTypeId: mgmt.id, amount: '1500', effectiveFrom: new Date('2024-01-01') },
      { organizationId: orgId, propertyId: p3.id, unitId: null, chargeTypeId: mgmt.id, amount: '800', effectiveFrom: new Date('2024-01-01') },
    ],
  });
  // The edits above saved without an address, which clears it, as the form does.
  await properties.update({ id: p1.id, name: BUILDING, address: '6/F, Sino ZZ Plaza, 9 ZZ Road' });
  const draft = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2026-01' });
  const mgmtLine = draft.lines.find((l) => l.chargeTypeId === mgmt.id);
  ck('C1 the fee is each unit at its own purchase’s figure: 1000 + 1500 + 800', mgmtLine?.amount.toFixed(2) === '3300.00', `got ${mgmtLine?.amount.toFixed(2)}`);
  const prefill = await leases.standardChargePrefill({ unitIds: [u611, u631], startDate: '2026-01-01' });
  ck('C2 a new lease is offered each unit’s own purchase’s figure',
    prefill.rules.find((r) => r.unitId === u611)?.amount === '1000.00' && prefill.rules.find((r) => r.unitId === u631)?.amount === '800.00',
    JSON.stringify(prefill.rules.map((r) => `${r.unitName}=${r.amount}`)));
  await billing.issue({ organizationId: orgId, invoiceId: draft.id });
  const issued = await prisma.invoice.findUniqueOrThrow({ where: { id: draft.id }, select: { number: true, letterheadSnapshot: true } });
  ck('C3 the debit note is numbered under the units’ company', issued.number === 'ZZBP-ZW00001', `got ${issued.number}`);
  ck('C4 and headed by the letterhead its purchases agree on', (issued.letterheadSnapshot as { name?: string } | null)?.name === 'ZZ Building Purchase Org');
  const html = (await documents.invoiceHtml(orgId, draft.id)).html;
  ck('C5 the note names the units and the building', html.includes('611, 621, 631, Sino ZZ Plaza') && html.includes('9 ZZ Road'), /<div>[^<]*(611|Sino)[^<]*<\/div>/i.exec(html)?.[0] ?? 'no address block');
  const roll = (await reports.rentRoll(orgId)).groups.flatMap((g) => g.rows).find((r) => r.reference === leaseRef);
  ck('C6 the rent roll names the building and bills the fee by unit', roll?.propertyName === BUILDING && roll?.monthlyCharge === '33300.00', JSON.stringify(roll));
}

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