/**
 * Manual screenshot fixture — a whole office's worth of believable Hong Kong
 * data, built so every figure in the user manual can be photographed from a
 * real screen rather than mocked up.
 *
 * Deliberately separate from `demo-fixture.ts` (one walkable scenario) and from
 * the seed (configuration only): this one exists to fill twenty-seven pictures,
 * so it covers each state a screen can be in — every debit note status, every
 * deposit status, every reason a meter reading can be stuck.
 *
 * Everything that touches the ledger (debit notes, receipts, deposits) goes
 * through the services, never `prisma.create`, so the trial balance still
 * balances afterwards and the reports page has real numbers on it.
 *
 * Every row it writes is tagged so `--clear` can find it again: leases are
 * `MF-*`, meters are `MF-*`, and the properties, tenants and landlords are
 * named in the lists below. Nothing the seed or demo-fixture made is touched.
 *
 * Run: cd apps/api && npx dotenv -e ../../.env -- npx ts-node -P tsconfig.json scripts/manual-fixture.ts
 *      …same line with `--clear` to remove everything it made.
 */
import 'reflect-metadata';
import { randomBytes, scryptSync } from 'node:crypto';
import { PDFDocument, StandardFonts } from 'pdf-lib';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma, ReferenceDomain } from '@prisma/client';
import { ApprovalService } from '../src/approvals/approval.service';
import { AttachmentService } from '../src/attachments/attachment.service';
import { StorageService } from '../src/attachments/storage.service';
import { BillingService } from '../src/billing/billing.service';
import { invoiceArState } from '../src/billing/invoice-ar';
import { NumberService } from '../src/common/number.service';
import { accountTypeFor } from '../src/common/codes';
import { hkToday } from '../src/common/hk-date';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { MaintenanceService } from '../src/maintenance/maintenance.service';
import { MeteringService } from '../src/metering/metering.service';
import { NotificationService } from '../src/notifications/notification.service';
import { ChannelDispatcher } from '../src/notifications/channel.dispatcher';
import type { NotifyPayload } from '../src/notifications/notification.constants';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { recordStandardCharge, reviewStandardCharge } from '../src/standard-charges/standard-charge.service';
import type { AuthUser } from '../src/trpc/auth-user';

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 deposits = new DepositsService(prisma, ledger, numbers, approvals);
const metering = new MeteringService(prisma);
const storage = new StorageService(new ConfigService());
const maintenance = new MaintenanceService(prisma, events, storage);
const attachments = new AttachmentService(prisma, storage);
const notifications = new NotificationService(prisma, new ChannelDispatcher());

// No Nest container here, so the @OnEvent listener does not exist: without this
// line the maintenance transitions emit into nothing and the outbox stays empty.
events.on('notify', (p: NotifyPayload) => notifications.dispatch(p));

const db = prisma as unknown as Prisma.TransactionClient;

// ── what `--clear` recognises as ours ────────────────────────────────────────
const LEASE_PREFIX = 'MF-';
const METER_PREFIX = 'MF-';
const BANK_ACCOUNT_NO = '024-885001-MF';
const BANK_ACCOUNT_NO_2 = '004-552188-MF';
/** The two collection accounts' own accounts in the chart. Made up, and out of
 *  the ERP's range: the office's real bank accounts carry real numbers. */
const BANK_GL_CODES = ['1199-99-0001', '1199-99-0002'];
const REFUND_WORKFLOW_CODE = 'mf-refund';
const LANDLORD_CODES = ['MA', 'MB', 'MC'];
const PROPERTIES = ['全連商業大廈', '盛滙花園', '金碼工業中心', '康寧商場', '創富工業大廈'];
const TENANTS = ['恒昌貿易有限公司', '永泰科技有限公司', '明豐飲食集團有限公司', '康健醫療中心', '李家豪', '明德電子有限公司', '宏達物流有限公司'];
const LEASE_LABELS = ['續租洽談中', '重點客戶', '留意欠款'];
const PORTAL_EMAIL = 'tenant@rms.local';
const PORTAL_PASSWORD = process.env.DEMO_TENANT_PASSWORD ?? 'tenant123';
const PORTAL_TENANT = '恒昌貿易有限公司';

// ── calendar helpers: everything is relative to today, so the "not due yet" and
//    "waiting to be billed" readings keep meaning what the manual says they mean.
const TODAY = hkToday();
const mStart = (offset: number): Date => new Date(Date.UTC(TODAY.getUTCFullYear(), TODAY.getUTCMonth() + offset, 1));
const iso = (d: Date): string => d.toISOString().slice(0, 10);
const period = (offset: number): string => iso(mStart(offset)).slice(0, 7);
const addDays = (d: Date, n: number): Date => new Date(d.getTime() + n * 86_400_000);
const dayBefore = (d: Date): Date => addDays(d, -1);
/** A fixed calendar date, as every date here is stored: UTC midnight. */
const utc = (iso: string): Date => new Date(`${iso}T00:00:00.000Z`);

/** Same scrypt$salt$hash format the seed and the auth module use. */
function hashPassword(plain: string): string {
  const salt = randomBytes(16).toString('hex');
  return `scrypt$${salt}$${scryptSync(plain, salt, 64).toString('hex')}`;
}

/** The management company's letter: a real page, since the debit note that
 *  first bills the new fee appends it after its own. */
async function noticeLetter(effectiveFrom: string): Promise<Buffer> {
  const doc = await PDFDocument.create();
  const page = doc.addPage([595, 842]);
  const font = await doc.embedFont(StandardFonts.Helvetica);
  const bold = await doc.embedFont(StandardFonts.HelveticaBold);
  const line = (text: string, y: number, f = font, size = 11) => page.drawText(text, { x: 60, y, size, font: f });
  line('ALL LINK PROPERTY MANAGEMENT LIMITED', 770, bold, 14);
  line('Chuen Lin Commercial Building, 88 Des Voeux Road Central, Hong Kong', 752);
  line('NOTICE TO ALL TENANTS', 700, bold, 13);
  line('Adjustment of Management Fee', 682, bold);
  line(`With effect from ${effectiveFrom}, the monthly management fee will be HK$2,640.00 per unit`, 650);
  line('(previously HK$2,400.00), in view of the increased costs of security and cleaning.', 634);
  line('Building Manager', 560);
  return Buffer.from(await doc.save());
}

function fakePdf(title: string): Buffer {
  return Buffer.from(
    `%PDF-1.4\n% ${title}\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 0>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n`,
    'utf8',
  );
}

// ════════════════════════════════════════════════════════════════════════════
// clear
// ════════════════════════════════════════════════════════════════════════════
async function clear(): Promise<void> {
  const org = await prisma.organization.findUnique({ where: { code: 'MAIN' }, select: { id: true } });
  if (!org) return;
  const orgId = org.id;

  const ids = async <T extends { id: string }>(rows: T[]): Promise<string[]> => rows.map((r) => r.id);
  const propIds = await ids(await prisma.property.findMany({ where: { organizationId: orgId, name: { in: PROPERTIES } }, select: { id: true } }));
  const tenantIds = await ids(await prisma.tenant.findMany({ where: { organizationId: orgId, name: { in: TENANTS } }, select: { id: true } }));
  const leaseIds = await ids(await prisma.lease.findMany({ where: { reference: { startsWith: LEASE_PREFIX } }, select: { id: true } }));
  const unitIds = await ids(await prisma.unit.findMany({ where: { propertyId: { in: propIds } }, select: { id: true } }));
  const meterIds = await ids(await prisma.meter.findMany({ where: { serialNo: { startsWith: METER_PREFIX } }, select: { id: true } }));
  const readingIds = await ids(await prisma.meterReading.findMany({ where: { meterId: { in: meterIds } }, select: { id: true } }));
  const invIds = await ids(await prisma.invoice.findMany({ where: { leaseId: { in: leaseIds } }, select: { id: true } }));
  const lineIds = await ids(await prisma.invoiceLine.findMany({ where: { invoiceId: { in: invIds } }, select: { id: true } }));
  const depIds = await ids(await prisma.deposit.findMany({ where: { OR: [{ leaseId: { in: leaseIds } }, { tenantId: { in: tenantIds } }] }, select: { id: true } }));
  const setIds = await ids(await prisma.depositSettlement.findMany({ where: { depositId: { in: depIds } }, select: { id: true } }));
  // Deposit receipts by their lease as well: one that has paid nothing yet
  // names no note, and would otherwise be left holding the lease in place.
  const rcpIds = await ids(await prisma.receipt.findMany({
    where: { OR: [{ allocations: { some: { items: { some: { invoiceId: { in: invIds } } } } } }, { leaseId: { in: leaseIds } }] },
    select: { id: true },
  }));
  const reqIds = await ids(await prisma.maintenanceRequest.findMany({ where: { propertyId: { in: propIds } }, select: { id: true } }));
  const noticeIds = await ids(await prisma.propertyNotice.findMany({ where: { propertyId: { in: propIds } }, select: { id: true } }));

  // Files first: the row is the record, the blob on disk is reachable no other
  // way, so both go together rather than leaving orphans under storage/uploads.
  const owned = await prisma.attachment.findMany({
    where: {
      organizationId: orgId,
      OR: [
        { ownerType: 'PROPERTY', ownerId: { in: propIds } },
        { ownerType: 'PROPERTY_NOTICE', ownerId: { in: noticeIds } },
        { ownerType: 'METER_READING', ownerId: { in: readingIds } },
        { ownerType: 'RECEIPT', ownerId: { in: rcpIds } },
        { ownerType: 'INVOICE', ownerId: { in: invIds } },
        { ownerType: 'INVOICE_LINE', ownerId: { in: lineIds } },
        { ownerType: 'MAINTENANCE_REQUEST', ownerId: { in: reqIds } },
      ],
    },
    select: { id: true, storageKey: true },
  });
  for (const a of owned) {
    await prisma.attachment.delete({ where: { id: a.id } });
    await storage.remove(a.storageKey).catch(() => undefined);
  }

  await prisma.notificationOutbox.deleteMany({ where: { organizationId: orgId, relatedId: { in: [...reqIds, ...invIds, ...rcpIds] } } });

  const docIds = [...invIds, ...depIds, ...setIds];
  await prisma.approvalAction.deleteMany({ where: { instance: { documentId: { in: docIds } } } });
  await prisma.approvalInstance.deleteMany({ where: { documentId: { in: docIds } } });

  // Ledger: a reversal points at what it reverses (Restrict), so those go first.
  const entries = await prisma.journalEntry.findMany({
    where: { OR: [{ sourceId: { in: [...invIds, ...depIds, ...setIds, ...rcpIds, ...leaseIds] } }, { lines: { some: { invoiceId: { in: invIds } } } }] },
    select: { id: true, reversesId: true },
  });
  const entryIds = entries.map((e) => e.id);
  await prisma.journalLine.deleteMany({ where: { entryId: { in: entryIds } } });
  await prisma.journalLine.deleteMany({ where: { OR: [{ invoiceId: { in: invIds } }, { leaseId: { in: leaseIds } }] } });
  await prisma.journalEntry.deleteMany({ where: { id: { in: entries.filter((e) => e.reversesId).map((e) => e.id) } } });
  await prisma.journalEntry.deleteMany({ where: { id: { in: entryIds } } });

  await prisma.maintenanceTask.deleteMany({ where: { requestId: { in: reqIds } } });
  await prisma.maintenanceRequest.deleteMany({ where: { id: { in: reqIds } } });

  await prisma.depositSettlementLine.deleteMany({ where: { settlementId: { in: setIds } } });
  await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
  await prisma.depositSettlement.deleteMany({ where: { id: { in: setIds } } });
  await prisma.deposit.deleteMany({ where: { id: { in: depIds } } });

  await prisma.receiptAllocationItem.deleteMany({ where: { invoiceId: { in: invIds } } });
  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 } } });

  await prisma.meterReading.deleteMany({ where: { id: { in: readingIds } } });
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
  await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });

  await prisma.plannedCharge.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.leaseLabelOnLease.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.leaseUtilitySetting.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.propertyNotice.deleteMany({ where: { id: { in: noticeIds } } });
  await prisma.lease.updateMany({ where: { id: { in: leaseIds } }, data: { renewedFromId: null } });
  await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  await prisma.leaseLabel.deleteMany({ where: { organizationId: orgId, name: { in: LEASE_LABELS } } });

  await prisma.standardCharge.deleteMany({ where: { propertyId: { in: propIds } } });
  await prisma.meterUnit.deleteMany({ where: { meterId: { in: meterIds } } });
  await prisma.meter.deleteMany({ where: { id: { in: meterIds } } });
  await prisma.utilityTariff.deleteMany({ where: { propertyId: { in: propIds } } });

  await prisma.unit.deleteMany({ where: { id: { in: unitIds } } });
  await prisma.property.deleteMany({ where: { id: { in: propIds } } });
  await prisma.tenant.deleteMany({ where: { id: { in: tenantIds } } });
  await prisma.landlord.deleteMany({ where: { organizationId: orgId, code: { in: LANDLORD_CODES } } });

  const wf = await prisma.approvalWorkflow.findFirst({
    where: { organizationId: orgId, documentType: 'DEPOSIT_REFUND', code: REFUND_WORKFLOW_CODE },
    select: { id: true },
  });
  if (wf) {
    await prisma.approvalAction.deleteMany({ where: { instance: { workflowId: wf.id } } });
    await prisma.approvalInstance.deleteMany({ where: { workflowId: wf.id } });
    await prisma.approvalStep.deleteMany({ where: { workflowId: wf.id } });
    await prisma.approvalWorkflow.delete({ where: { id: wf.id } });
  }

  const ourBanks = { accountNumber: { in: [BANK_ACCOUNT_NO, BANK_ACCOUNT_NO_2] } };
  await prisma.invoice.updateMany({ where: { bankAccount: ourBanks }, data: { bankAccountId: null } });
  await prisma.lease.updateMany({ where: { bankAccount: ourBanks }, data: { bankAccountId: null } });
  await prisma.bankAccount.deleteMany({ where: { organizationId: orgId, ...ourBanks } });
  // Unless something the fixture did not make has posted to them since.
  await prisma.glAccount.deleteMany({ where: { organizationId: orgId, code: { in: BANK_GL_CODES }, journalLines: { none: {} } } });

  // Hand the portal login back to whichever tenant the seed gave it.
  const seeded = await prisma.tenant.findFirst({ where: { organizationId: orgId }, orderBy: { createdAt: 'asc' }, select: { id: true } });
  if (seeded) await prisma.user.updateMany({ where: { email: PORTAL_EMAIL }, data: { tenantId: seeded.id, name: 'Chan Tai Man' } });
}

// ════════════════════════════════════════════════════════════════════════════
// create
// ════════════════════════════════════════════════════════════════════════════
const made: Record<string, number> = {};
const tally = (k: string, n = 1): void => {
  made[k] = (made[k] ?? 0) + n;
};

async function create(): Promise<void> {
  const org = await prisma.organization.findUnique({ where: { code: 'MAIN' }, select: { id: true } });
  if (!org) throw new Error('No MAIN organization — run `npm run prisma:seed` first.');
  const orgId = org.id;

  // ── lookups ───────────────────────────────────────────────────────────────
  const ct = async (code: string): Promise<string> =>
    (await prisma.chargeType.findUniqueOrThrow({ where: { organizationId_code: { organizationId: orgId, code } }, select: { id: true } })).id;
  const RENT = await ct('RENT');
  const MGMT = await ct('MGMT_FEE');
  const RATES = await ct('RATES');
  const GOV_RENT = await ct('GOV_RENT');
  const STAMP = await ct('STAMP_DUTY');
  const WATER = await ct('WATER');
  const ELEC = await ct('ELECTRICITY');
  const GAS = await ct('GAS');
  const RM = await ct('RM');
  const CONCESSION = await ct('CONCESSION');

  const ref = async (domain: string, code: string): Promise<string> =>
    (await prisma.referenceValue.findFirstOrThrow({
      where: { organizationId: orgId, domain: domain as ReferenceDomain, code },
      select: { id: true },
    })).id;
  const FIXED_TERM = await ref('LEASE_TYPE', 'FIXED_TERM');
  const USAGE_OFFICE = await ref('LEASE_USAGE', 'OFFICE');
  const USAGE_RETAIL = await ref('LEASE_USAGE', 'RETAIL');
  const USAGE_RESI = await ref('LEASE_USAGE', 'RESIDENTIAL');
  const USAGE_WAREHOUSE = await ref('LEASE_USAGE', 'WAREHOUSE');
  const CAT_COMMERCIAL = await ref('PROPERTY_CATEGORY', 'COMMERCIAL');
  const CAT_RESIDENTIAL = await ref('PROPERTY_CATEGORY', 'RESIDENTIAL');
  const CAT_INDUSTRIAL = await ref('PROPERTY_CATEGORY', 'INDUSTRIAL');

  const admin = await prisma.user.findUniqueOrThrow({ where: { email: 'admin@rms.local' }, select: { id: true, email: true, name: true } });
  const leasing = await prisma.user.findFirst({
    where: { isActive: true, tenantId: null, deletedAt: null, roles: { some: { role: { code: 'LEASING' } } } },
    select: { id: true, name: true, email: true },
  });
  const accounting = await prisma.user.findFirst({
    where: { isActive: true, tenantId: null, deletedAt: null, roles: { some: { role: { code: 'ACCOUNTING' } } } },
    select: { id: true, name: true, email: true },
  });
  if (!leasing || !accounting) throw new Error('No LEASING / ACCOUNTING login to sign approvals with — run the seed first.');

  const method = async (code: string): Promise<string> =>
    (await prisma.settlementMethod.findUniqueOrThrow({ where: { code }, select: { id: true } })).id;
  const CASH = await method('CASH');
  const CHEQUE = await method('CHEQUE');
  const TRANSFER = await method('BANK_TRANSFER');
  const FPS = await method('FPS');

  const filer: AuthUser = {
    id: admin.id,
    email: admin.email,
    name: admin.name,
    tenantId: null,
    mustChangePassword: false,
    roles: ['ADMIN'],
    permissions: ['property.read', 'property.update', 'notice.read', 'notice.update', 'maintenance.update'],
  };

  // ── where the money is collected (frozen onto every note as it is issued) ──
  //    Each posts to its own bank account in the chart, as in the ERP.
  const bankGl = async (code: string, name: string) =>
    (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type: 'ASSET', isBank: true }, select: { id: true } })).id;
  const bank = await prisma.bankAccount.create({
    data: {
      organizationId: orgId,
      name: '恒生銀行 — 租金收款戶口',
      bankName: '恒生銀行有限公司',
      accountName: 'ALL LINK PROPERTY MANAGEMENT LIMITED',
      accountNumber: BANK_ACCOUNT_NO,
      isCollectionAgent: true,
      isActive: true,
      glAccountId: await bankGl(BANK_GL_CODES[0], '恒生銀行 — 租金收款戶口(示範)'),
    },
    select: { id: true },
  });
  await prisma.bankAccount.create({
    data: {
      organizationId: orgId,
      name: '滙豐銀行 — 管理費收款戶口',
      bankName: '香港上海滙豐銀行有限公司',
      accountName: 'ALL LINK PROPERTY MANAGEMENT LIMITED',
      accountNumber: BANK_ACCOUNT_NO_2,
      isCollectionAgent: false,
      isActive: true,
      glAccountId: await bankGl(BANK_GL_CODES[1], '滙豐銀行 — 管理費收款戶口(示範)'),
    },
  });
  tally('bankAccount', 2);

  // ── landlords ─────────────────────────────────────────────────────────────
  const landlordSpecs = [
    { code: 'MA', name: 'All Link International Limited', nameZh: '全連國際有限公司', account: '1810-13-0000', address: '香港中環德輔道中 88 號全連大廈 12 樓', tel: '2523 0001', email: 'info@alllink.example', sortOrder: 10 },
    { code: 'MB', name: 'Blossom Properties Limited', nameZh: '盛滙置業有限公司', account: '1810-46-0000', address: '九龍觀塘鴻圖道 35 號 8 樓', tel: '2790 0002', email: null, sortOrder: 20 },
    { code: 'MC', name: 'Golden Wharf Holdings Limited', nameZh: '金碼集團有限公司', account: null, address: null, tel: null, email: null, sortOrder: 30 },
  ];
  // A landlord's account is its current account in the chart, found by code —
  // and added if the ERP's chart has not been imported here.
  const accountOf = async (code: string, name: string) =>
    (await prisma.glAccount.findFirst({ where: { organizationId: orgId, code }, select: { id: true } }))?.id ??
    (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type: accountTypeFor(code) } })).id;
  const ll = new Map<string, string>();
  for (const { account, ...l } of landlordSpecs) {
    const glAccountId = account ? await accountOf(account, l.name) : null;
    const row = await prisma.landlord.create({ data: { organizationId: orgId, ...l, glAccountId, isActive: true }, select: { id: true, code: true } });
    ll.set(row.code, row.id);
  }
  tally('landlord', landlordSpecs.length);

  // ── properties + units ────────────────────────────────────────────────────
  // Each property is one purchase: its number (typed, so a re-load lands on the
  // same ones the manual's pictures show), the day it completed, the price, and
  // the government lease as the land search states it.
  interface Purchase {
    code: string;
    completionDate: string;
    purchasePrice: string;
    landLeaseTerm: string;
    landLeaseCommencement: string;
    saleCompletionDate?: string;
    salePrice?: string;
  }
  const mkProperty = (
    name: string,
    address: string,
    code: string,
    categoryId: string,
    letterheadSource: 'ORGANIZATION' | 'LANDLORD',
    units: { name: string; area: string }[],
    purchase: Purchase,
  ) =>
    prisma.property.create({
      data: {
        organizationId: orgId,
        name,
        address,
        landlordId: ll.get(code) ?? null,
        categoryId,
        letterheadSource,
        code: purchase.code,
        completionDate: utc(purchase.completionDate),
        purchasePrice: purchase.purchasePrice,
        saleCompletionDate: purchase.saleCompletionDate ? utc(purchase.saleCompletionDate) : null,
        salePrice: purchase.salePrice ?? null,
        landLeaseTerm: purchase.landLeaseTerm,
        landLeaseCommencement: utc(purchase.landLeaseCommencement),
        units: { create: units.map((u) => ({ name: u.name, area: u.area })) },
      },
      select: { id: true, name: true, units: { select: { id: true, name: true } } },
    });

  const pCom = await mkProperty('全連商業大廈', '香港中環德輔道中 88 號', 'MA', CAT_COMMERCIAL, 'LANDLORD', [
    { name: '5 樓 A 室', area: '820.00' },
    { name: '5 樓 B 室', area: '760.00' },
    { name: '6 樓 A 室', area: '820.00' },
    { name: '8 樓全層', area: '3200.00' },
  ], { code: 'P-MA970601', completionDate: '1997-06-30', purchasePrice: '38500000.00', landLeaseTerm: '999 years', landLeaseCommencement: '1843-06-26' });
  const pRes = await mkProperty('盛滙花園', '九龍觀塘鴻圖道 35 號', 'MB', CAT_RESIDENTIAL, 'ORGANIZATION', [
    { name: 'A 座 12 樓 1 室', area: '540.00' },
    { name: 'A 座 12 樓 2 室', area: '560.00' },
    { name: 'B 座 3 樓 1 室', area: '498.00' },
  ], { code: 'P-MB081101', completionDate: '2008-11-14', purchasePrice: '12600000.00', landLeaseTerm: '75 years renewable for 75 years', landLeaseCommencement: '1956-07-01' });
  const pInd = await mkProperty('金碼工業中心', '新界葵涌大連排道 12 號', 'MC', CAT_INDUSTRIAL, 'ORGANIZATION', [
    { name: '3 樓 A 室', area: '2400.00' },
    { name: '3 樓 B 室', area: '2400.00' },
  ], { code: 'P-MC120301', completionDate: '2012-03-30', purchasePrice: '26800000.00', landLeaseTerm: '99 years less the last 3 days', landLeaseCommencement: '1898-07-01' });
  const pShop = await mkProperty('康寧商場', '九龍旺角亞皆老街 120 號', 'MB', CAT_COMMERCIAL, 'LANDLORD', [
    { name: '地下 1 號舖', area: '680.00' },
    { name: '地下 2 號舖', area: '420.00' },
    { name: '2 樓 5 號舖', area: '300.00' },
  ], { code: 'P-MB030901', completionDate: '2003-09-12', purchasePrice: '45000000.00', landLeaseTerm: '75 years renewable for 75 years', landLeaseCommencement: '1924-09-01' });
  // The same mall bought a second time, years later: one more shop, same
  // company, same letterhead — so a lease can take units of both purchases.
  const pShop2 = await mkProperty('康寧商場', '九龍旺角亞皆老街 120 號', 'MB', CAT_COMMERCIAL, 'LANDLORD', [
    { name: '地下 3 號舖', area: '360.00' },
  ], { code: 'P-MB190401', completionDate: '2019-04-18', purchasePrice: '18800000.00', landLeaseTerm: '75 years renewable for 75 years', landLeaseCommencement: '1924-09-01' });
  // One tenant on 614–631, billed on eight notes a month; 611–613 another's; the
  // pantry a unit only so its meter has somewhere to hang (a meter needs one).
  const facUnits = Array.from({ length: 21 }, (_, i) => ({ name: String(611 + i), area: '650.00' }));
  const pFac = await mkProperty('創富工業大廈', '香港九龍觀塘鴻圖道 58 號', 'MA', CAT_INDUSTRIAL, 'LANDLORD', [...facUnits, { name: '茶水間', area: '180.00' }],
    { code: 'P-MA150501', completionDate: '2015-05-29', purchasePrice: '98000000.00', landLeaseTerm: '99 years', landLeaseCommencement: '1898-07-01' });
  // A lorry space in the basement, bought on its own and since sold: listed as
  // sold, its unit no longer offered to a new lease.
  const pFacPark = await mkProperty('創富工業大廈', '香港九龍觀塘鴻圖道 58 號 地庫', 'MA', CAT_INDUSTRIAL, 'LANDLORD', [{ name: '地庫 L7 貨車停車位', area: '0.00' }],
    { code: 'P-MA160801', completionDate: '2016-08-26', purchasePrice: '1800000.00', landLeaseTerm: '99 years', landLeaseCommencement: '1898-07-01', saleCompletionDate: '2026-03-31', salePrice: '2350000.00' });
  tally('property', 7);
  tally('unit', [pCom, pRes, pInd, pShop, pShop2, pFac, pFacPark].reduce((n, p) => n + p.units.length, 0));

  const unit = (p: { units: { id: string; name: string }[] }, name: string): string => p.units.find((u) => u.name === name)!.id;
  const u5A = unit(pCom, '5 樓 A 室');
  const u5B = unit(pCom, '5 樓 B 室');
  const u6A = unit(pCom, '6 樓 A 室');
  const u8F = unit(pCom, '8 樓全層');
  const uRes1 = unit(pRes, 'A 座 12 樓 1 室');
  const uRes2 = unit(pRes, 'A 座 12 樓 2 室');
  const uRes3 = unit(pRes, 'B 座 3 樓 1 室');
  const uInd1 = unit(pInd, '3 樓 A 室');
  const shop1 = unit(pShop, '地下 1 號舖');
  const shop2 = unit(pShop, '地下 2 號舖');
  const facUnit = (name: string): string => unit(pFac, name);
  const xiaomiUnits = facUnits.map((u) => u.name).filter((n) => Number(n) >= 614);

  // ── utility rates. Set BEFORE any reading exists, so the building left
  //    without one keeps its readings unpriced ("未設費率" on the metering page).
  const tariff = (chargeTypeId: string, propertyId: string, unitRate: string, fixedCharge: string) =>
    metering.setTariff({ organizationId: orgId, chargeTypeId, propertyId, unitRate, fixedCharge });
  await tariff(WATER, pCom.id, '5.900000', '18.00');
  await tariff(ELEC, pCom.id, '1.420000', '0.00');
  await tariff(GAS, pCom.id, '0.960000', '11.50');
  await tariff(WATER, pRes.id, '4.580000', '12.00');
  await tariff(ELEC, pRes.id, '1.280000', '0.00');
  await tariff(WATER, pShop.id, '6.200000', '24.00');
  await tariff(ELEC, pFac.id, '1.500000', '0.00');
  // 金碼工業中心 deliberately has no rate at all; 康寧商場 has no electricity rate.
  tally('utilityTariff', 7);

  // ── tenants ───────────────────────────────────────────────────────────────
  const tenantSpecs = [
    { name: TENANTS[0], nameZh: '恒昌貿易有限公司', attention: '王淑儀小姐', email: 'ap@hangcheong.example', phone: '2345 6789' },
    { name: TENANTS[1], nameZh: '永泰科技有限公司', attention: '陳志明先生', email: 'finance@wingtai.example', phone: '2811 3344' },
    { name: TENANTS[2], nameZh: '明豐飲食集團有限公司', attention: '李寶琳經理', email: 'accounts@mingfung.example', phone: '2760 8899' },
    { name: TENANTS[3], nameZh: '康健醫療中心', attention: '張偉強醫生', email: 'admin@hongkin.example', phone: '2388 1200' },
    { name: TENANTS[4], nameZh: '李家豪', attention: null, email: 'leekaho@example.com', phone: '9123 4567' },
    { name: TENANTS[5], nameZh: '明德電子有限公司', attention: '陳小姐', email: 'ap@mingtak.example', phone: '2793 6688' },
    { name: TENANTS[6], nameZh: '宏達物流有限公司', attention: '黃先生', email: 'accounts@wangtat.example', phone: '2345 1122' },
  ];
  const tn = new Map<string, string>();
  for (const t of tenantSpecs) {
    const row = await prisma.tenant.create({ data: { organizationId: orgId, ...t }, select: { id: true, name: true } });
    tn.set(row.name, row.id);
  }
  tally('tenant', tenantSpecs.length);

  // Their codes in each landlord company's ERP books, one per company they rent
  // from — so 明豐 and 李家豪, with leases under two, have two. Typed rather than
  // suggested: these names are Chinese, which leaves the suggestion no letters.
  // Where the office has keyed the account, it is the receivables account.
  const debtors = (await prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, role: 'RECEIVABLE' }, select: { id: true } })).id;
  const tenantCodes: [string, string, string, boolean][] = [
    [TENANTS[0], 'MA', 'MAHANG01', true],
    [TENANTS[1], 'MB', 'MBWING01', true],
    [TENANTS[2], 'MB', 'MBMING01', true],
    [TENANTS[2], 'MC', 'MCMING01', false],
    [TENANTS[3], 'MA', 'MAHONG01', true],
    [TENANTS[4], 'MA', 'MALEEK01', false],
    [TENANTS[4], 'MB', 'MBLEEK01', false],
    [TENANTS[5], 'MA', 'MAMTAK01', true],
    [TENANTS[6], 'MA', 'MAWANG01', true],
  ];
  await prisma.tenantCode.createMany({
    data: tenantCodes.map(([tenant, landlord, code, keyed]) => ({ organizationId: orgId, tenantId: tn.get(tenant)!, landlordId: ll.get(landlord)!, code, glAccountId: keyed ? debtors : null })),
  });

  // ── leases ────────────────────────────────────────────────────────────────
  interface RuleSpec {
    chargeTypeId: string;
    unitId?: string;
    amount: string;
    frequencyMonths?: number;
    timing?: 'ADVANCE' | 'ARREARS';
    proration?: 'DAILY' | 'FULL_MONTH';
    firstInvoiceOnly?: boolean;
    /** Billed at the property's standard charge (standard-billing.ts). */
    followsStandard?: boolean;
  }
  const mkLease = async (opts: {
    reference: string;
    tenantName: string;
    unitIds: string[];
    status: 'DRAFT' | 'ACTIVE' | 'ENDED';
    startDate: Date;
    endDate: Date;
    depositMonths: number;
    dueDayOfMonth: number;
    usageId: string;
    noticeDays: number;
    note?: string;
    rentFreeFrom?: Date;
    rentFreeTo?: Date;
    renewedFromId?: string;
    /** Each unit's billing group, by unit id: a group's units share a monthly note. */
    billingGroups?: Record<string, string>;
    rules: RuleSpec[];
  }) => {
    const row = await prisma.lease.create({
      data: {
        organizationId: orgId,
        reference: opts.reference,
        tenantId: tn.get(opts.tenantName)!,
        bankAccountId: bank.id,
        status: opts.status,
        currency: 'HKD',
        startDate: opts.startDate,
        endDate: opts.endDate,
        rentFreeFrom: opts.rentFreeFrom ?? null,
        rentFreeTo: opts.rentFreeTo ?? null,
        depositMonths: opts.depositMonths,
        dueDayOfMonth: opts.dueDayOfMonth,
        leaseTypeId: FIXED_TERM,
        usageId: opts.usageId,
        noticeDays: opts.noticeDays,
        note: opts.note ?? null,
        renewedFromId: opts.renewedFromId ?? null,
        units: { create: opts.unitIds.map((unitId) => ({ unitId, billingGroup: opts.billingGroups?.[unitId] ?? null })) },
        chargeRules: {
          create: opts.rules.map((r, i) => ({
            chargeTypeId: r.chargeTypeId,
            unitId: r.unitId ?? null,
            amount: r.amount,
            frequencyMonths: r.frequencyMonths ?? 1,
            timing: r.timing ?? 'ADVANCE',
            proration: r.proration ?? 'DAILY',
            firstInvoiceOnly: r.firstInvoiceOnly ?? false,
            followsStandard: r.followsStandard ?? false,
            sortOrder: i,
          })),
        },
      },
      select: { id: true, reference: true, tenantId: true },
    });
    if (opts.status === 'ACTIVE') await prisma.unit.updateMany({ where: { id: { in: opts.unitIds } }, data: { status: 'OCCUPIED' } });
    tally('lease');
    return row;
  };

  const L1 = await mkLease({
    reference: 'MF-L001', tenantName: TENANTS[0], unitIds: [u5A],
    status: 'ACTIVE', startDate: mStart(-9), endDate: dayBefore(mStart(15)),
    depositMonths: 2, dueDayOfMonth: 10, usageId: USAGE_OFFICE, noticeDays: 60,
    note: '冷氣機由業主保養;續租條款另行商議。',
    rules: [
      { chargeTypeId: RENT, amount: '48000.00' },
      { chargeTypeId: MGMT, unitId: u5A, amount: '4800.00', proration: 'FULL_MONTH' },
      { chargeTypeId: RATES, amount: '7200.00', frequencyMonths: 3 },
      { chargeTypeId: STAMP, amount: '3840.00', proration: 'FULL_MONTH', firstInvoiceOnly: true },
      { chargeTypeId: WATER, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });

  const L2 = await mkLease({
    reference: 'MF-L002', tenantName: TENANTS[1], unitIds: [shop1, shop2],
    status: 'ACTIVE', startDate: mStart(-5), endDate: dayBefore(mStart(19)),
    depositMonths: 3, dueDayOfMonth: 1, usageId: USAGE_RETAIL, noticeDays: 90,
    note: '兩個舖位打通經營;首 45 日為裝修期,免租金。',
    rentFreeFrom: mStart(-5), rentFreeTo: addDays(mStart(-5), 44),
    rules: [
      { chargeTypeId: RENT, unitId: shop1, amount: '62000.00', proration: 'FULL_MONTH' },
      { chargeTypeId: RENT, unitId: shop2, amount: '38000.00', proration: 'FULL_MONTH' },
      { chargeTypeId: MGMT, amount: '9000.00' },
      { chargeTypeId: RATES, amount: '5400.00', frequencyMonths: 3 },
      { chargeTypeId: STAMP, amount: '4000.00', proration: 'FULL_MONTH', firstInvoiceOnly: true },
      { chargeTypeId: WATER, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });

  const L3 = await mkLease({
    reference: 'MF-L003', tenantName: TENANTS[2], unitIds: [uRes1],
    status: 'ACTIVE', startDate: mStart(0), endDate: dayBefore(mStart(24)),
    depositMonths: 2, dueDayOfMonth: 5, usageId: USAGE_RESI, noticeDays: 60,
    note: '首 45 日為裝修期,免租金;管理費及差餉照繳。',
    rentFreeFrom: mStart(0), rentFreeTo: addDays(mStart(0), 44),
    rules: [
      { chargeTypeId: RENT, amount: '52000.00' },
      { chargeTypeId: MGMT, amount: '5200.00', proration: 'FULL_MONTH' },
      { chargeTypeId: RATES, amount: '4500.00', frequencyMonths: 3 },
    ],
  });

  const L4 = await mkLease({
    reference: 'MF-L004', tenantName: TENANTS[3], unitIds: [u8F],
    status: 'ACTIVE', startDate: mStart(-15), endDate: dayBefore(mStart(9)),
    depositMonths: 2, dueDayOfMonth: 10, usageId: USAGE_OFFICE, noticeDays: 60,
    rules: [
      { chargeTypeId: RENT, amount: '36000.00' },
      { chargeTypeId: MGMT, amount: '3600.00', proration: 'FULL_MONTH' },
    ],
  });

  const L7 = await mkLease({
    reference: 'MF-L007', tenantName: TENANTS[3], unitIds: [u6A],
    status: 'ACTIVE', startDate: mStart(-7), endDate: dayBefore(mStart(17)),
    depositMonths: 2, dueDayOfMonth: 15, usageId: USAGE_OFFICE, noticeDays: 60,
    rules: [
      { chargeTypeId: RENT, amount: '26000.00' },
      // At the building's standard, and following it: the announced 2,640 reaches
      // this lease by itself, its notice on the note that first bills it.
      { chargeTypeId: MGMT, unitId: u6A, amount: '2400.00', proration: 'FULL_MONTH', followsStandard: true },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });

  const L6 = await mkLease({
    reference: 'MF-L006', tenantName: TENANTS[4], unitIds: [u5B],
    status: 'ENDED', startDate: mStart(-32), endDate: dayBefore(mStart(-8)),
    depositMonths: 2, dueDayOfMonth: 15, usageId: USAGE_OFFICE, noticeDays: 30,
    note: '租約期滿,租客不續租,已交吉。',
    rules: [
      { chargeTypeId: RENT, amount: '18000.00' },
      { chargeTypeId: MGMT, amount: '1800.00', proration: 'FULL_MONTH' },
    ],
  });

  const L8 = await mkLease({
    reference: 'MF-L008', tenantName: TENANTS[4], unitIds: [uRes3],
    status: 'ENDED', startDate: mStart(-27), endDate: dayBefore(mStart(0)),
    depositMonths: 2, dueDayOfMonth: 10, usageId: USAGE_RESI, noticeDays: 30,
    note: '已交吉,等候按金結算。',
    rules: [{ chargeTypeId: RENT, amount: '24000.00' }],
  });

  const L9 = await mkLease({
    reference: 'MF-L009', tenantName: TENANTS[2], unitIds: [uInd1],
    status: 'ENDED', startDate: mStart(-36), endDate: dayBefore(mStart(-1)),
    depositMonths: 3, dueDayOfMonth: 10, usageId: USAGE_WAREHOUSE, noticeDays: 90,
    note: '中央廚房遷出,已交吉。',
    rules: [{ chargeTypeId: RENT, amount: '40000.00' }],
  });

  // Eight notes a month: 614, 615, 616 one each, 617–622, 623–627, 628–629, then
  // 630 and 631 one each. Rent and management fee are for the whole lease, so
  // each note takes its units' part of them (180,000 ÷ 18 = 10,000 a unit).
  const groupOf = (n: number): string => (n <= 616 ? String(n - 613) : n <= 622 ? '4' : n <= 627 ? '5' : n <= 629 ? '6' : String(n - 623));
  const L10 = await mkLease({
    reference: 'MF-L010', tenantName: TENANTS[5], unitIds: xiaomiUnits.map(facUnit),
    status: 'ACTIVE', startDate: mStart(-3), endDate: dayBefore(mStart(21)),
    depositMonths: 0, dueDayOfMonth: 1, usageId: USAGE_OFFICE, noticeDays: 90,
    note: '十八個單位分八張請款單;電費按中電總錶扣茶水間同 611–613 分錶,分六份。',
    billingGroups: Object.fromEntries(xiaomiUnits.map((n) => [facUnit(n), groupOf(Number(n))])),
    rules: [
      { chargeTypeId: RENT, amount: '180000.00', proration: 'FULL_MONTH' },
      { chargeTypeId: MGMT, amount: '27000.00', proration: 'FULL_MONTH' },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });
  await mkLease({
    reference: 'MF-L011', tenantName: TENANTS[6], unitIds: ['611', '612', '613'].map(facUnit),
    status: 'ACTIVE', startDate: mStart(-2), endDate: dayBefore(mStart(22)),
    depositMonths: 0, dueDayOfMonth: 1, usageId: USAGE_WAREHOUSE, noticeDays: 60,
    rules: [
      { chargeTypeId: RENT, amount: '30000.00', proration: 'FULL_MONTH' },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });

  // The renewal is a FUTURE draft on purpose: the monthly run activates any
  // draft renewal whose start date has arrived, and that would take the picture.
  const L5 = await mkLease({
    reference: 'MF-L005', tenantName: TENANTS[0], unitIds: [u5A],
    status: 'DRAFT', startDate: mStart(15), endDate: dayBefore(mStart(39)),
    depositMonths: 2, dueDayOfMonth: 10, usageId: USAGE_OFFICE, noticeDays: 60,
    note: '續租兩年,租金上調 6%。免租期不予延續。', renewedFromId: L1.id,
    rules: [
      { chargeTypeId: RENT, amount: '51000.00' },
      { chargeTypeId: MGMT, unitId: u5A, amount: '5100.00', proration: 'FULL_MONTH' },
      { chargeTypeId: RATES, amount: '7600.00', frequencyMonths: 3 },
      { chargeTypeId: WATER, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
      { chargeTypeId: ELEC, amount: '0.00', timing: 'ARREARS', proration: 'FULL_MONTH' },
    ],
  });

  // ── labels ────────────────────────────────────────────────────────────────
  const label = async (name: string): Promise<string> =>
    (await prisma.leaseLabel.upsert({ where: { organizationId_name: { organizationId: orgId, name } }, update: {}, create: { organizationId: orgId, name } })).id;
  const lRenew = await label(LEASE_LABELS[0]);
  const lVip = await label(LEASE_LABELS[1]);
  const lWatch = await label(LEASE_LABELS[2]);
  await prisma.leaseLabelOnLease.createMany({
    data: [
      { leaseId: L1.id, labelId: lRenew },
      { leaseId: L1.id, labelId: lVip },
      { leaseId: L2.id, labelId: lVip },
      { leaseId: L7.id, labelId: lWatch },
    ],
  });

  // ── standard charges ──────────────────────────────────────────────────────
  const sc = (propertyId: string, unitId: string | null, chargeTypeId: string, amount: string, effectiveFrom: Date, note: string | null) =>
    recordStandardCharge(prisma, { organizationId: orgId, propertyId, unitId, chargeTypeId, amount, effectiveFrom, note, recordedByUserId: admin.id });
  await sc(pCom.id, null, MGMT, '2400.00', mStart(-21), '上一輪管理費');
  const scAnnounced = await sc(pCom.id, null, MGMT, '2640.00', mStart(2), '加幅 10%,已出信通知全幢租客');
  await sc(pCom.id, null, RATES, '1620.00', mStart(-5), '本年度差餉');
  await sc(pCom.id, null, GOV_RENT, '780.00', mStart(-5), null);
  await sc(pCom.id, u5B, MGMT, '2200.00', mStart(-14), '5 樓 B 室議定管理費');
  await sc(pRes.id, null, MGMT, '1680.00', mStart(-8), '盛滙花園管理費');
  tally('standardCharge', 6);

  const review = await reviewStandardCharge(prisma, orgId, scAnnounced.id);
  tally('reviewAffected', review.affected.length);
  tally('reviewSkipped', review.skipped.length);

  // ── notice letters ────────────────────────────────────────────────────────
  const nMgmt = await prisma.propertyNotice.create({
    data: {
      organizationId: orgId, propertyId: pCom.id, date: addDays(TODAY, -9),
      typeId: await ref('NOTICE_TYPE', 'MGMT_FEE_ADJUSTMENT'),
      remark: `已向全幢租客發出管理費調整通知,由 ${iso(mStart(2))} 起每月 2,640 元,加幅 10%。`,
      leaseId: null, standardChargeId: scAnnounced.id, recordedByUserId: admin.id,
    },
    select: { id: true },
  });
  await prisma.propertyNotice.create({
    data: {
      organizationId: orgId, propertyId: pCom.id, date: addDays(TODAY, -78),
      typeId: await ref('NOTICE_TYPE', 'CONTRIBUTION'),
      remark: '大廈外牆維修攤分,5 樓 A 室應分擔 12,800 元,分四期隨管理費收取。',
      leaseId: L1.id, standardChargeId: null, recordedByUserId: admin.id,
    },
  });
  await prisma.propertyNotice.create({
    data: {
      organizationId: orgId, propertyId: pRes.id, date: addDays(TODAY, -126),
      typeId: await ref('NOTICE_TYPE', 'OTHERS'),
      remark: '水缸清洗通知,當日上午停水四小時,請住戶預先儲水。',
      leaseId: null, standardChargeId: null, recordedByUserId: admin.id,
    },
  });
  tally('propertyNotice', 3);

  // ── property documents (real bytes, so the download on the page works) ─────
  const docs = [
    { prop: pCom.id, code: 'PASP', filename: '臨時買賣合約.pdf', caption: '1997-03-11 簽署' },
    { prop: pCom.id, code: 'SPA', filename: '正式買賣合約.pdf', caption: null },
    { prop: pCom.id, code: 'ASSIGNMENT', filename: '轉讓契.pdf', caption: '1997-06-30 完成' },
    { prop: pCom.id, code: 'TITLE_DEEDS', filename: '樓契.pdf', caption: '正本存於律師樓' },
    { prop: pCom.id, code: 'TITLE_DEEDS', filename: '樓契-補充文件.pdf', caption: '同一類別可以有多份' },
    { prop: pCom.id, code: 'MORTGAGE_DEED', filename: '按揭契.pdf', caption: '恒生銀行' },
    { prop: pRes.id, code: 'ASSIGNMENT', filename: '轉讓契-盛滙花園.pdf', caption: null },
    { prop: pRes.id, code: 'FLOOR_PLAN', filename: '樓面平面圖.pdf', caption: 'A 座 12 樓' },
    { prop: pInd.id, code: 'LAND_SEARCH', filename: '土地查冊.pdf', caption: '最新查冊' },
  ];
  for (const d of docs) {
    await attachments.upload({
      user: filer, organizationId: orgId, ownerType: 'PROPERTY', ownerId: d.prop,
      filename: d.filename, mimeType: 'application/pdf', buffer: fakePdf(d.filename),
      caption: d.caption, documentTypeId: await ref('PROPERTY_DOCUMENT_TYPE', d.code),
    });
  }
  await attachments.upload({
    user: filer, organizationId: orgId, ownerType: 'PROPERTY_NOTICE', ownerId: nMgmt.id,
    filename: '管理費調整通知書.pdf', mimeType: 'application/pdf',
    buffer: await noticeLetter(iso(mStart(2))), caption: '已寄出正本',
  });
  tally('attachment', docs.length + 1);

  // ── meters and staff readings, before any note is raised so they get billed ─
  const mkMeter = (chargeTypeId: string, serialNo: string, unitIds: string[], opts: { parentMeterId?: string; isActive?: boolean; shares?: Record<string, string> } = {}) =>
    prisma.meter.create({
      data: {
        chargeTypeId, serialNo,
        isActive: opts.isActive ?? true,
        parentMeterId: opts.parentMeterId ?? null,
        units: { create: unitIds.map((unitId) => ({ unitId, share: opts.shares?.[unitId] ?? '1' })) },
      },
      select: { id: true, serialNo: true },
    });
  const reading = (meterId: string, start: string, end: string, from: number, to: number, note?: string) =>
    metering.createReading({
      organizationId: orgId, meterId, readingStart: start, readingEnd: end,
      periodStart: iso(mStart(from)), periodEnd: iso(mStart(to)), note: note ?? null,
    });

  const mWater5A = await mkMeter(WATER, 'MF-W-5A-0071', [u5A]);
  const mGas5A = await mkMeter(GAS, 'MF-G-5A-0088', [u5A]);
  const mMaster = await mkMeter(ELEC, 'MF-E-MASTER-01', [u6A]);
  const mSub1 = await mkMeter(ELEC, 'MF-E-SUB-5A', [u5A], { parentMeterId: mMaster.id });
  const mSub2 = await mkMeter(ELEC, 'MF-E-SUB-5B', [u5B], { parentMeterId: mMaster.id });
  const mShops = await mkMeter(WATER, 'MF-W-SHOPS-02', [shop1, shop2]);
  const mVacant = await mkMeter(WATER, 'MF-W-RES2-03', [uRes2]);
  const mRetired = await mkMeter(WATER, 'MF-W-OLD-99', [uRes3], { isActive: false });
  const mNoRate = await mkMeter(ELEC, 'MF-E-IND-3A', [uInd1]);
  // CLP's master less the pantry and 611–613, split in six: 614, 615, 616,
  // 617–622 and 623–627 a sixth each, the last sixth three ways. Out of 36.
  const clpShare = (n: number): string => (n <= 616 ? '6' : n <= 622 ? '1' : n <= 627 ? '1.2' : n <= 629 ? '1' : '2');
  const mClp = await mkMeter(ELEC, 'MF-E-CLP-01', xiaomiUnits.map(facUnit), {
    shares: Object.fromEntries(xiaomiUnits.map((n) => [facUnit(n), clpShare(Number(n))])),
  });
  // The pantry is billed to no one: it is read only to come off the master.
  const mPantry = await mkMeter(ELEC, 'MF-E-PANTRY', [facUnit('茶水間')], { parentMeterId: mClp.id, shares: { [facUnit('茶水間')]: '0' } });
  const m611 = await mkMeter(ELEC, 'MF-E-611-613', ['611', '612', '613'].map(facUnit), { parentMeterId: mClp.id });
  tally('meter', 12);

  // 5A water: one that a note will pick up, one for next month's note, one not due yet
  await reading(mWater5A.id, '1200.000', '1560.000', -5, -4, '抄錶員實地抄');
  await reading(mWater5A.id, '1560.000', '1895.000', -4, -3);
  await reading(mWater5A.id, '1895.000', '2210.000', -1, 0, '本期讀數,下月出單');
  // master + sub meters: a clean period, one where the subs overrun, one waiting
  // on a sub. Waiting is the latest on purpose: a sub-meter reading after it
  // would count as read up to its date (metering/sub-meter-deduction.ts).
  await reading(mMaster.id, '0.000', '1000.000', -3, -2);
  await reading(mSub1.id, '0.000', '300.000', -3, -2);
  await reading(mSub2.id, '0.000', '200.000', -3, -2);
  await reading(mMaster.id, '1000.000', '1050.000', -2, -1);
  await reading(mSub1.id, '300.000', '500.000', -2, -1);
  await reading(mSub2.id, '200.000', '260.000', -2, -1);
  await reading(mMaster.id, '1050.000', '1850.000', -1, 0, '分錶 MF-E-SUB-5B 未抄');
  await reading(mSub1.id, '500.000', '610.000', -1, 0);
  // the shop meter covers two units — one reading, split evenly, still queued
  await reading(mShops.id, '480.000', '702.000', -2, -1);
  // each blocked for its own reason
  await reading(mGas5A.id, '12.000', '31.500', -2, -1, '租約冇煤氣收費規則');
  await reading(mVacant.id, '0.000', '8.250', -2, -1, '吉單位');
  await reading(mRetired.id, '400.000', '455.000', -2, -1, '舊錶已停用');
  await reading(mNoRate.id, '80.000', '215.000', -2, -1, '金碼工業中心未設電費費率');
  // Last month to its last day, so this month's notes take them: 12,000 less
  // 600 and 2,400 is 9,000 at 1.5 — 13,500, a sixth of it 2,250.
  const lastMonth = (meterId: string, start: string, end: string) =>
    metering.createReading({
      organizationId: orgId, meterId, readingStart: start, readingEnd: end,
      periodStart: iso(mStart(-1)), periodEnd: iso(dayBefore(mStart(0))), note: null,
    });
  await lastMonth(mClp.id, '50000.000', '62000.000');
  await lastMonth(mPantry.id, '3000.000', '3600.000');
  await lastMonth(m611.id, '20000.000', '22400.000');
  tally('meterReading', 19);

  // ════════════════════════════════════════════════════════════════════════
  // debit notes — every status the list can show
  // ════════════════════════════════════════════════════════════════════════
  const owed = async (invoiceId: string): Promise<string> => (await invoiceArState(db, orgId, invoiceId)).outstanding.toFixed(2);

  async function walkApproval(invoiceId: string, steps: number): Promise<void> {
    await billing.submitForApproval({ organizationId: orgId, invoiceId });
    const signers = [
      { userId: leasing!.id, note: '租賃部已核對租金及管理費' },
      { userId: accounting!.id, note: '會計部確認可出' },
    ];
    for (const s of signers.slice(0, steps)) {
      const inst = await prisma.approvalInstance.findFirst({
        where: { documentType: 'INVOICE', documentId: invoiceId, isComplete: false, cancelledAt: null },
        select: { id: true },
      });
      if (!inst) break;
      await approvals.act({ organizationId: orgId, userId: s.userId, instanceId: inst.id, action: 'APPROVE', note: s.note });
    }
  }
  const issueNote = async (leaseId: string, p: string, unitIds?: string[]) => {
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId, period: p, ...(unitIds ? { unitIds } : {}) });
    await walkApproval(draft.id, 2);
    tally('invoice');
    return billing.issue({ organizationId: orgId, invoiceId: draft.id, issuedByUserId: accounting.id });
  };

  // MF-L001 — the portal tenant's own run of notes
  const invPaid = await issueNote(L1.id, period(-4));
  const invRich = await (async () => {
    const draft = await billing.generateDraft({ organizationId: orgId, leaseId: L1.id, period: period(-3) });
    await billing.addAdjustment({ organizationId: orgId, invoiceId: draft.id, chargeTypeId: CONCESSION, description: '冷氣停機三日租金優惠', amount: '4645.00', credit: true });
    await billing.addAdjustment({ organizationId: orgId, invoiceId: draft.id, chargeTypeId: RM, description: '更換冷氣濾網(單位自付)', amount: '850.00', credit: false });
    await walkApproval(draft.id, 2);
    tally('invoice');
    return billing.issue({ organizationId: orgId, invoiceId: draft.id, issuedByUserId: accounting.id });
  })();
  const invPartial = await issueNote(L1.id, period(-2));
  const invOpen = await issueNote(L1.id, period(-1));
  const invPending = await billing.generateDraft({ organizationId: orgId, leaseId: L1.id, period: period(0) });
  await walkApproval(invPending.id, 1); // one signature in, one still to go
  tally('invoice');

  // MF-L002 — one voided after issue, one split note covering a single shop
  const invVoid = await issueNote(L2.id, period(-2));
  await billing.voidInvoice({ organizationId: orgId, invoiceId: invVoid.id });
  const invSplit = await issueNote(L2.id, period(-1), [shop1]);

  // MF-L003 — approved, deliberately not issued yet
  const invApproved = await billing.generateDraft({ organizationId: orgId, leaseId: L3.id, period: period(0) });
  await walkApproval(invApproved.id, 2);
  tally('invoice');

  // MF-L007 — an issued note carried forward onto next month's draft
  const invCarrySource = await issueNote(L7.id, period(-1));
  await billing.generateDraft({ organizationId: orgId, leaseId: L7.id, period: period(0) });
  tally('invoice');
  await billing.carryForward({ organizationId: orgId, invoiceId: invCarrySource.id, targetPeriod: period(0), carriedByUserId: accounting.id });

  // MF-L008 — the last month's note, still owed when the keys came back. Without
  // it the move-out settlement screen has nothing to set against the deposit and
  // shows only its empty "no outstanding notes" line. Raised the way it was in
  // life — while the tenancy was still running — then put back to ENDED.
  await prisma.lease.update({ where: { id: L8.id }, data: { status: 'ACTIVE' } });
  await issueNote(L8.id, period(-1));
  await prisma.lease.update({ where: { id: L8.id }, data: { status: 'ENDED' } });

  // ── the portal login, pointed at the tenant whose screens the manual shows ─
  const tenantRole = await prisma.role.findUniqueOrThrow({ where: { code: 'TENANT' }, select: { id: true } });
  const portalUser = await prisma.user.upsert({
    where: { email: PORTAL_EMAIL },
    update: {
      passwordHash: hashPassword(PORTAL_PASSWORD),
      mustChangePassword: false, isActive: true, deletedAt: null,
      tenantId: tn.get(PORTAL_TENANT)!, locale: 'zh-HK', name: '王淑儀',
    },
    create: {
      email: PORTAL_EMAIL, name: '王淑儀', passwordHash: hashPassword(PORTAL_PASSWORD),
      locale: 'zh-HK', tenantId: tn.get(PORTAL_TENANT)!, roles: { create: { roleId: tenantRole.id } },
    },
    select: { id: true },
  });
  await prisma.userRole.upsert({
    where: { userId_roleId: { userId: portalUser.id, roleId: tenantRole.id } },
    update: {}, create: { userId: portalUser.id, roleId: tenantRole.id },
  });

  // ── receipts: every status the list can show ──────────────────────────────
  const fullPaid = await owed(invPaid.id);
  const rApproved = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: L1.tenantId, amount: fullPaid,
    settlementMethodId: CASH, receivedDate: addDays(mStart(-4), 7),
    note: '租客到辦公室繳付現金', uploadedByUserId: accounting.id,
    allocations: [{ invoiceId: invPaid.id, amount: fullPaid }],
  });
  await payments.approve({ organizationId: orgId, receiptId: rApproved.id, reviewedByUserId: accounting.id });
  tally('receipt');

  const rPart = await payments.recordBulkPayment({
    organizationId: orgId, tenantId: L1.tenantId, amount: '20000.00',
    settlementMethodId: TRANSFER, reference: 'FT26071500123', receivedDate: addDays(mStart(-2), 14),
    note: '客戶先找一半', uploadedByUserId: accounting.id,
    allocations: [{ invoiceId: invPartial.id, amount: '20000.00' }],
  });
  await payments.approve({ organizationId: orgId, receiptId: rPart.id, reviewedByUserId: accounting.id });
  tally('receipt');

  // a cheque that cleared and then bounced — the note goes back to fully owed
  const rBounced = await payments.submitReceipt({
    organizationId: orgId, tenantId: L1.tenantId, invoiceId: invOpen.id,
    amount: '5000.00', settlementMethodId: CHEQUE, reference: 'CHQ 028817', uploadedByUserId: portalUser.id,
  });
  await prisma.receipt.update({ where: { id: rBounced.id }, data: { receivedDate: addDays(mStart(-1), 5) } });
  await payments.approve({ organizationId: orgId, receiptId: rBounced.id, reviewedByUserId: accounting.id });
  await payments.bounce({ organizationId: orgId, receiptId: rBounced.id, reason: '支票存款不足,銀行退票。', reviewedByUserId: accounting.id });
  // bounce() keeps its reason in the internal note; the portal reads rejectionReason
  await prisma.receipt.update({ where: { id: rBounced.id }, data: { rejectionReason: '支票存款不足,銀行退票,請改用轉數快繳付。' } });
  tally('receipt');

  const rRejected = await payments.submitReceipt({
    organizationId: orgId, tenantId: L1.tenantId, invoiceId: invOpen.id,
    amount: '3000.00', settlementMethodId: CASH, uploadedByUserId: portalUser.id,
  });
  await prisma.receipt.update({ where: { id: rRejected.id }, data: { receivedDate: addDays(mStart(-1), 12) } });
  await payments.reject({
    organizationId: orgId, receiptId: rRejected.id,
    reason: '上載嘅入數紙影得太矇,睇唔到金額同日期,請重新上載。', reviewedByUserId: accounting.id,
  });
  tally('receipt');

  const rWaiting = await payments.submitReceipt({
    organizationId: orgId, tenantId: L1.tenantId, invoiceId: invOpen.id,
    amount: '12000.00', settlementMethodId: FPS, reference: '7788 6612', uploadedByUserId: portalUser.id,
  });
  await prisma.receipt.update({ where: { id: rWaiting.id }, data: { receivedDate: addDays(TODAY, -2) } });
  tally('receipt');

  // ── deposit receipts: the first month of the renewal, paid at signing ──────
  // On the renewal, which has no note yet, so approving one pays nothing and
  // leaves every other picture as it was; the list shows it held in full.
  const drSigned = await payments.recordDepositReceipt({
    organizationId: orgId, tenantId: L5.tenantId, leaseId: L5.id, amount: '51000.00',
    settlementMethodId: CHEQUE, reference: 'CHQ 031204', receivedDate: addDays(TODAY, -6),
    note: '續租簽約時預繳首月租金', uploadedByUserId: accounting.id,
  });
  await payments.approve({ organizationId: orgId, receiptId: drSigned.id, reviewedByUserId: accounting.id });
  await payments.recordDepositReceipt({
    organizationId: orgId, tenantId: L5.tenantId, leaseId: L5.id, amount: '5100.00',
    settlementMethodId: FPS, reference: '7790 1185', receivedDate: addDays(TODAY, -1),
    note: '預繳首月管理費', uploadedByUserId: accounting.id,
  });
  tally('depositReceipt', 2);

  // ── tenant-declared readings (only the portal user can own these) ──────────
  await prisma.meterReading.create({
    data: {
      meterId: mWater5A.id, readingStart: '2210.000', readingEnd: '2465.000',
      periodStart: mStart(0), periodEnd: addDays(TODAY, -1),
      status: 'PENDING', submittedByUserId: portalUser.id,
    },
  });
  await prisma.meterReading.create({
    data: {
      meterId: mWater5A.id, readingStart: '2210.000', readingEnd: '2180.000',
      periodStart: mStart(0), periodEnd: addDays(TODAY, -10),
      status: 'REJECTED', submittedByUserId: portalUser.id, reviewedByUserId: admin.id,
      rejectionReason: '相中讀數細過上期嘅 2210,應該係睇漏咗最前面嗰個位,請重新影過。',
    },
  });
  tally('meterReading', 2);

  // ════════════════════════════════════════════════════════════════════════
  // deposits
  // ════════════════════════════════════════════════════════════════════════
  const adminRoleId = (await prisma.role.findUniqueOrThrow({ where: { code: 'ADMIN' }, select: { id: true } })).id;
  const acctRoleId = (await prisma.role.findUniqueOrThrow({ where: { code: 'ACCOUNTING' }, select: { id: true } })).id;
  const refundWorkflow = await prisma.approvalWorkflow.create({
    data: {
      organizationId: orgId, documentType: 'DEPOSIT_REFUND', code: REFUND_WORKFLOW_CODE,
      name: '按金退款審批', minAmount: '20000.00', isActive: true,
      steps: {
        create: [
          { stepOrder: 1, name: '物業部覆核', actorType: 'ROLE', actorRoleId: adminRoleId },
          { stepOrder: 2, name: '會計部批核', actorType: 'ROLE', actorRoleId: acctRoleId },
        ],
      },
    },
    select: { id: true },
  });
  tally('approvalWorkflow');

  const mkDeposit = async (leaseId: string, tenantId: string, amount: string, receivedDate: Date, note: string) => {
    const d = await deposits.create({ organizationId: orgId, tenantId, leaseId, amount, receivedDate: iso(receivedDate), receivedByUserId: accounting.id });
    await prisma.deposit.update({ where: { id: d.id }, data: { note } });
    tally('deposit');
    return d;
  };

  await mkDeposit(L1.id, L1.tenantId, '96000.00', addDays(mStart(-9), 4), '兩個月租金按金');
  const dpL2 = await mkDeposit(L2.id, L2.tenantId, '300000.00', addDays(mStart(-5), 3), '三個月租金按金');
  await mkDeposit(L3.id, L3.tenantId, '104000.00', addDays(mStart(0), 1), '兩個月租金按金');
  const dpL4 = await mkDeposit(L4.id, L4.tenantId, '72000.00', addDays(mStart(-15), 5), '兩個月租金按金');
  const dpL6 = await mkDeposit(L6.id, L6.tenantId, '36000.00', addDays(mStart(-32), 6), '兩個月租金按金');
  await mkDeposit(L8.id, L8.tenantId, '48000.00', addDays(mStart(-27), 2), '兩個月租金按金,等候結算');
  const dpL9 = await mkDeposit(L9.id, L9.tenantId, '120000.00', addDays(mStart(-36), 3), '三個月租金按金');

  // partly set against a note that is still owed
  await deposits.apply({ organizationId: orgId, depositId: dpL2.id, invoiceId: invSplit.id, amount: '25000.00', appliedByUserId: accounting.id });

  // the lease that ended early — terminate through the service so the final
  // note is pro-rated to the day the tenancy actually stopped
  await billing.terminateLease({
    organizationId: orgId, leaseId: L4.id, terminationDate: dayBefore(mStart(-2)),
    reason: '租客提早退租,已繳付代通知金一個月。',
  });
  tally('invoice'); // terminate raises the final pro-rated draft

  await deposits.settle({
    organizationId: orgId, depositId: dpL4.id,
    charges: [
      { description: '牆身修補及油漆', chargeTypeId: RM, amount: '8000.00' },
      { description: '交吉清潔', chargeTypeId: RM, amount: '4000.00' },
    ],
    note: '交吉當日已聯同租客點算。', settledByUserId: accounting.id,
  });
  await deposits.submitRefundForApproval({ organizationId: orgId, depositId: dpL4.id });

  await deposits.settle({
    organizationId: orgId, depositId: dpL9.id,
    charges: [{ description: '地台修補及油漆', chargeTypeId: RM, amount: '15000.00' }],
    note: '工業單位交吉,地台有損耗。', settledByUserId: accounting.id,
  });
  await deposits.submitRefundForApproval({ organizationId: orgId, depositId: dpL9.id });

  // a second deposit on the same tenancy — utilities rather than rent, settled
  // and still to be paid out: under the threshold, so the refund screen shows
  // the payout form rather than the approval gate.
  const dpL6b = await mkDeposit(L6.id, L6.tenantId, '12000.00', addDays(mStart(-32), 6), '水電及雜費按金');
  await deposits.settle({
    organizationId: orgId, depositId: dpL6b.id,
    charges: [{ description: '未結水電費', chargeTypeId: RM, amount: '3000.00' }],
    note: '尚欠兩期水電,已於按金扣除。', settledByUserId: accounting.id,
  });

  // the rent deposit on the same tenancy, refunded in full through the bank
  await deposits.settle({
    organizationId: orgId, depositId: dpL6.id,
    charges: [
      { description: '冷氣機維修', chargeTypeId: RM, amount: '18000.00' },
      { description: '交吉清潔及棄置傢俬', chargeTypeId: RM, amount: '10000.00' },
    ],
    note: '租約期滿交吉。', settledByUserId: accounting.id,
  });
  await deposits.disburseRefund({
    organizationId: orgId, depositId: dpL6.id, settlementMethodId: CHEQUE,
    reference: 'CHQ 900231', disbursedByUserId: accounting.id,
  });

  // ════════════════════════════════════════════════════════════════════════
  // maintenance
  // ════════════════════════════════════════════════════════════════════════
  const mkRequest = async (opts: {
    propertyId: string; unitId: string; tenantId: string; leaseId: string;
    category: string; priority: string; title: string; description: string;
    costResponsibility: 'LANDLORD' | 'TENANT' | 'SPLIT'; tenantSharePercent?: string;
    estimatedCost: string; to?: string[]; actualCost?: string;
  }) => {
    const r = await maintenance.create({
      organizationId: orgId, propertyId: opts.propertyId, unitId: opts.unitId,
      tenantId: opts.tenantId, leaseId: opts.leaseId,
      categoryId: await ref('MAINTENANCE_CATEGORY', opts.category),
      priorityId: await ref('MAINTENANCE_PRIORITY', opts.priority),
      title: opts.title, description: opts.description,
      costResponsibility: opts.costResponsibility,
      tenantSharePercent: opts.tenantSharePercent ?? '100',
      estimatedCost: opts.estimatedCost, reportedByUserId: portalUser.id,
    });
    for (const s of opts.to ?? []) await maintenance.transition({ organizationId: orgId, id: r.id, toStatus: s });
    if (opts.actualCost) await maintenance.update({ organizationId: orgId, id: r.id, actualCost: opts.actualCost });
    tally('maintenanceRequest');
    return r;
  };

  const mr1 = await mkRequest({
    propertyId: pCom.id, unitId: u5A, tenantId: L1.tenantId, leaseId: L1.id,
    category: 'PLUMBING', priority: 'HIGH', title: '廚房去水位滲水',
    description: '洗手盆下方去水喉接口滲水,租客已用膠桶接住。',
    costResponsibility: 'LANDLORD', estimatedCost: '1200',
  });
  const mr2 = await mkRequest({
    propertyId: pCom.id, unitId: u5A, tenantId: L1.tenantId, leaseId: L1.id,
    category: 'HVAC', priority: 'URGENT', title: '會議室冷氣不制冷',
    description: '壓縮機老化,業主與租客各自承擔一部分。',
    costResponsibility: 'SPLIT', tenantSharePercent: '60', estimatedCost: '4500',
    to: ['ACKNOWLEDGED', 'IN_PROGRESS'], actualCost: '4380',
  });
  // The proof behind it, which goes onto the debit note when it is charged.
  for (const d of [
    { code: 'REPAIR_SLIP', filename: '冷氣維修單.pdf', caption: '師傅現場簽收' },
    { code: 'SUPPLIER_RECEIPT', filename: '供應商收據.pdf', caption: '冷氣公司 INV-118' },
  ]) {
    await attachments.upload({
      user: filer, organizationId: orgId, ownerType: 'MAINTENANCE_REQUEST', ownerId: mr2.id,
      filename: d.filename, mimeType: 'application/pdf', buffer: fakePdf(d.filename),
      caption: d.caption, documentTypeId: await ref('MAINTENANCE_DOCUMENT_TYPE', d.code),
    });
  }
  tally('attachment', 2);
  const mr3 = await mkRequest({
    propertyId: pCom.id, unitId: u5A, tenantId: L1.tenantId, leaseId: L1.id,
    category: 'ELECTRICAL', priority: 'NORMAL', title: '茶水間抽氣扇燒壞',
    description: '租客報稱有燒焦味,已即時停用。',
    costResponsibility: 'TENANT', estimatedCost: '2000',
    to: ['ACKNOWLEDGED', 'IN_PROGRESS', 'COMPLETED'], actualCost: '2150',
  });
  const mr4 = await mkRequest({
    propertyId: pShop.id, unitId: shop1, tenantId: L2.tenantId, leaseId: L2.id,
    category: 'APPLIANCE', priority: 'NORMAL', title: '舖面捲閘卡死',
    description: '捲閘落到一半卡住,暫時人手開關。',
    costResponsibility: 'TENANT', estimatedCost: '850', to: ['ACKNOWLEDGED'],
  });
  await mkRequest({
    propertyId: pRes.id, unitId: uRes1, tenantId: L3.tenantId, leaseId: L3.id,
    category: 'PEST', priority: 'LOW', title: '後樓梯有木蝨',
    description: '管理處已安排滅蟲公司上門。',
    costResponsibility: 'LANDLORD', estimatedCost: '1500',
    to: ['ACKNOWLEDGED', 'IN_PROGRESS', 'COMPLETED', 'CLOSED'], actualCost: '1350',
  });

  const task = async (requestId: string, title: string, opts: { assignedToId?: string; assignedVendor?: string; day: number; note?: string; status?: string }) => {
    const t = await maintenance.addTask({
      organizationId: orgId, requestId, title,
      assignedToId: opts.assignedToId ?? null, assignedVendor: opts.assignedVendor ?? null,
      scheduledDate: iso(addDays(TODAY, opts.day)), note: opts.note ?? null,
    });
    if (opts.status) await maintenance.updateTask({ organizationId: orgId, taskId: t.id, status: opts.status });
    tally('maintenanceTask');
  };
  await task(mr1.id, '上門檢查去水喉接口', { assignedToId: leasing.id, day: 2, note: '已約租客下午 2:00。' });
  await task(mr2.id, '更換冷氣機壓縮機', { assignedVendor: '永興冷氣工程有限公司', day: -6, note: '已落單,零件下星期到。', status: 'IN_PROGRESS' });
  await task(mr2.id, '完工後清洗風槽', { assignedToId: leasing.id, day: 9 });
  await task(mr3.id, '拆換茶水間抽氣扇', { assignedVendor: '德昌電業工程', day: -12, note: '已完成,租客已簽收。', status: 'DONE' });
  // the same request carries a colleague's order too, at a different stage: this
  // is the one the manual photographs, and it is also the one with cost recovery
  await task(mr3.id, '核對供應商單據並入成本', { assignedToId: accounting.id, day: -3, note: '單據已收妥,待入帳。', status: 'IN_PROGRESS' });
  await task(mr4.id, '捲閘路軌校正', { assignedVendor: '安泰五金工程', day: 4 });

  // cost recovery — raises its own draft note, then sends it for approval
  const recovery = await maintenance.chargeToTenant({ organizationId: orgId, id: mr3.id });
  await billing.submitForApproval({ organizationId: orgId, invoiceId: recovery.invoiceId });
  tally('invoice');

  // ── planned charges: months that have not been billed yet ──────────────────
  const plan = (leaseId: string, chargeTypeId: string, p: string, description: string, amount: string, unitId: string | null = null) =>
    prisma.plannedCharge.create({ data: { organizationId: orgId, leaseId, chargeTypeId, unitId, period: p, description, amount, createdByUserId: admin.id } });
  await plan(L1.id, RM, period(1), '大堂玻璃門維修分攤', '1250.00');
  await plan(L1.id, RM, period(2), '外牆維修攤分(第一期)', '3200.00');
  await plan(L1.id, STAMP, period(1), '補加租金印花稅', '760.00');
  await plan(L2.id, RM, period(1), '地庫清洗渠務', '2400.00', shop1);
  tally('plannedCharge', 4);

  // ── one delivered notification, so the outbox is not all "skipped" ─────────
  const tpl = await prisma.notificationTemplate.findFirst({
    where: { organizationId: orgId, event: 'INVOICE_ISSUED', channel: 'EMAIL', isActive: true },
    select: { subject: true, body: true },
  });
  if (tpl) {
    await prisma.notificationOutbox.create({
      data: {
        organizationId: orgId, event: 'INVOICE_ISSUED', channel: 'EMAIL',
        recipient: 'ap@hangcheong.example',
        subject: tpl.subject ?? `請款單 ${invOpen.number ?? ''}`,
        body: tpl.body, status: 'SENT', relatedType: 'INVOICE', relatedId: invOpen.id,
        sentAt: addDays(mStart(-1), 1),
      },
    });
  }

  // ── MF-L010: three of this month's eight notes, raised by hand, last so they
  //    head the list — the CLP reading then reads "partly billed, 617–631 to go".
  for (const n of ['614', '615', '616']) {
    await billing.generateDraft({ organizationId: orgId, leaseId: L10.id, period: period(0), unitIds: [facUnit(n)] });
    tally('invoice');
  }

  // ── what the screenshots can now be taken from ────────────────────────────
  const refundPending = await prisma.approvalInstance.count({ where: { workflowId: refundWorkflow.id, isComplete: false, cancelledAt: null } });
  const byStatus = await prisma.lease.groupBy({ by: ['status'], where: { reference: { startsWith: LEASE_PREFIX } }, _count: true });
  const leaseMix = byStatus.map((s) => `${s._count} ${s.status.toLowerCase()}`).join(' · ');
  console.log('Manual fixture ready:');
  console.log(`  landlords   ${made.landlord} · properties ${made.property} (${made.unit} units) · tenants ${made.tenant}`);
  console.log(`  leases      ${made.lease} — MF-L001…MF-L011: ${leaseMix} (the draft is the renewal of MF-L001; MF-L010 bills on eight notes a month)`);
  console.log(`  charges     ${made.standardCharge} standard charges — one announced for ${period(2)}, ${made.reviewAffected ?? 0} lease(s) in its review, ${made.reviewSkipped ?? 0} skipped`);
  console.log(`  letters     ${made.propertyNotice} notices · ${made.attachment} filed documents`);
  console.log(`  metering    ${made.meter} meters (two masters with 2 subs each, one shared by share, a retired one) · ${made.meterReading} readings`);
  console.log(`  debit notes ${made.invoice} — draft / awaiting approval / approved / issued / part-paid / paid / void, incl. ${invRich.number} with adjustments and utilities`);
  console.log(`  receipts    ${made.receipt} — pending / approved / rejected / bounced`);
  console.log(`  deposit rcp ${made.depositReceipt} — one approved and held for the renewal, one pending`);
  console.log(`  deposits    ${made.deposit} — held / part-applied / settled / refunded · ${refundPending} refund(s) awaiting approval`);
  console.log(`  maintenance ${made.maintenanceRequest} requests · ${made.maintenanceTask} work orders · 1 charged back to the tenant`);
  console.log(`  planned     ${made.plannedCharge} charges queued for ${period(1)}–${period(2)}`);
  console.log(`  portal      ${PORTAL_EMAIL} / ${process.env.DEMO_TENANT_PASSWORD ? '<DEMO_TENANT_PASSWORD>' : 'tenant123'} — now ${PORTAL_TENANT}`);
  console.log(`  approvals   admin@rms.local for the deposit refunds · ${leasing.email} / ${accounting.email} for the debit notes`);
}

const mode = process.argv.includes('--clear') ? 'clear' : 'create';

(async () => {
  await clear();
  if (mode === 'create') await create();
  else console.log('Manual fixture removed.');
})()
  .catch((e) => {
    console.error(e instanceof Error ? (e.stack ?? e.message) : e);
    process.exitCode = 1;
  })
  .finally(() => prisma.$disconnect());
