import type { PrismaClient } from '@prisma/client';
import { accountTypeFor, isAccountCode, landlordCode, tenantCode } from '../common/codes';
import type { XlsxReadSheet } from '../common/xlsx-read';
import type { AuthUser } from '../trpc/auth-user';
import { chargeTypesRouter } from '../trpc/routers/charge-types.router';
import { landlordsRouter } from '../trpc/routers/landlords.router';
import { leasesRouter } from '../trpc/routers/leases.router';
import { propertiesRouter } from '../trpc/routers/properties.router';
import { referenceValuesRouter } from '../trpc/routers/reference-values.router';
import { tenantsRouter } from '../trpc/routers/tenants.router';
import type { Context } from '../trpc/trpc';
import { LABELS, MASTER_SHEETS, fromLabel, isPlaceholder, parseCell, splitList, type MasterSheetKey } from './master-data.workbook';

type Cell = string | number | boolean | null;
interface Row {
  line: number;
  v: Record<string, Cell>;
}
export type ParsedWorkbook = Record<MasterSheetKey, Row[]>;

/** The workbook could not be loaded; every reason found, not just the first. */
export class MasterDataProblems extends Error {
  constructor(readonly problems: string[]) {
    super(`${problems.length} problem(s) in the workbook`);
  }
}

/** The master-data sheets of a workbook, each row read by its column's kind.
 *  A sheet that is not there is empty; a sheet the system does not know (the
 *  notes, a checklist) is ignored. */
export function parseMasterWorkbook(sheets: readonly XlsxReadSheet[]): { data: ParsedWorkbook; problems: string[] } {
  const problems: string[] = [];
  const data = {} as ParsedWorkbook;
  for (const def of MASTER_SHEETS) {
    data[def.key] = [];
    const sheet = sheets.find((s) => s.name.trim() === def.name);
    if (!sheet) continue;
    const [head = [], ...body] = sheet.rows;
    const at = new Map(head.map((h, i) => [h.trim(), i]));
    const missing = def.columns.filter((c) => c.required && !at.has(c.header));
    if (missing.length) {
      problems.push(`「${def.name}」缺少欄位:${missing.map((c) => c.header).join('、')}`);
      continue;
    }
    body.forEach((cells, i) => {
      const line = i + 2;
      if (cells.every((c) => !c?.trim())) return;
      const v: Row['v'] = {};
      for (const c of def.columns) {
        const idx = at.get(c.header);
        try {
          v[c.key] = parseCell(c.kind, idx === undefined ? '' : (cells[idx] ?? ''));
        } catch (e) {
          problems.push(`「${def.name}」第 ${line} 行「${c.header}」:${e instanceof Error ? e.message : e}`);
          v[c.key] = null;
          continue;
        }
        if (c.required && v[c.key] === null) problems.push(`「${def.name}」第 ${line} 行「${c.header}」不可留空`);
      }
      data[def.key].push({ line, v });
    });
  }
  return { data, problems };
}

export interface ImportSummary {
  created: Partial<Record<MasterSheetKey, number>>;
  /** Already in the database and left as they are (option values, charge types, tenants). */
  kept: string[];
  /** Account codes the chart did not have, added named by their code — as the
   *  landlord import does — until the ERP's chart is imported over them. */
  addedAccounts: string[];
}

const text = (c: Cell | undefined): string | null => (c === null || c === undefined ? null : String(c).trim() || null);
const str = (c: Cell | undefined): string => text(c) ?? '';
const amount = (c: Cell | undefined): string | null => (typeof c === 'number' ? c.toFixed(2) : null);
const EMAIL = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/;

/**
 * Loads a parsed workbook into an organisation that has no properties or
 * leases yet — a new database. Everything is checked first and nothing is
 * written while anything is wrong. Then each record is made through the same
 * calls the back office's own screens make, so it is checked, numbered and
 * stored exactly as one keyed in would be.
 *
 * The calls are not one transaction: should one fail part-way (a database
 * error, not a problem in the file), the organisation is left part-loaded, and
 * the way back is a fresh database.
 */
export async function importMasterData(
  prisma: PrismaClient,
  organizationId: string,
  data: ParsedWorkbook,
  opts: { dryRun?: boolean } = {},
): Promise<ImportSummary> {
  const org = { organizationId };
  // Properties and leases, not tenants: a new database's seed makes one demo
  // tenant for the portal's demo login, and a live system always has both.
  const [properties, leases] = await Promise.all([prisma.property.count({ where: org }), prisma.lease.count({ where: org })]);
  if (properties + leases > 0) {
    throw new MasterDataProblems([`這個資料庫已經有 ${properties} 個物業、${leases} 份租約 —— 主檔只可以匯入未有物業和租約的新資料庫。`]);
  }

  const problems: string[] = [];
  const at = (sheet: MasterSheetKey, row: Row) => `「${MASTER_SHEETS.find((s) => s.key === sheet)!.name}」第 ${row.line} 行`;

  // ── what the database already has ──
  const [dbOptions, dbChargeTypes, dbLandlords, accounts, banks, dbTenants] = await Promise.all([
    prisma.referenceValue.findMany({ where: org, select: { domain: true, code: true, nameZh: true, nameEn: true } }),
    prisma.chargeType.findMany({ where: org, select: { code: true } }),
    prisma.landlord.findMany({ where: org, select: { id: true, code: true, address: true } }),
    prisma.glAccount.findMany({ where: org, select: { id: true, code: true } }),
    prisma.bankAccount.findMany({ where: org, select: { id: true, name: true } }),
    prisma.tenant.findMany({ where: { ...org, deletedAt: null }, select: { id: true, name: true } }),
  ]);
  const accountId = new Map(accounts.map((a) => [a.code, a.id]));
  const bankId = new Map(banks.map((b) => [b.name.trim().toLowerCase(), b.id]));
  const missingAccounts = new Set<string>();
  const account = (sheet: MasterSheetKey, row: Row, header: string, c: Cell | undefined): string | null => {
    const code = text(c);
    if (!code || accountId.has(code)) return code;
    if (!isAccountCode(code)) problems.push(`${at(sheet, row)}「${header}」:科目表沒有「${code}」,亦不是會計科目編號(格式 1234-56-7890)`);
    else missingAccounts.add(code);
    return code;
  };

  // ── option lists ──
  type Domain = keyof typeof LABELS.domain;
  const options: { domain: Domain; code: string; nameZh: string | null; nameEn: string; sortOrder: number; isActive: boolean; row: Row }[] = [];
  for (const row of data.options) {
    const domain = fromLabel('domain', str(row.v.domain)) as Domain | undefined;
    if (!domain) {
      problems.push(`${at('options', row)}「清單」:「${str(row.v.domain)}」不是 ${Object.values(LABELS.domain).join(' / ')}`);
      continue;
    }
    const code = str(row.v.code).toUpperCase();
    if (options.some((o) => o.domain === domain && o.code === code)) problems.push(`${at('options', row)}:${LABELS.domain[domain]}「${code}」重複`);
    options.push({ domain, code, nameZh: text(row.v.nameZh), nameEn: str(row.v.nameEn), sortOrder: Number(row.v.sortOrder ?? 0), isActive: row.v.isActive !== false, row });
  }
  /** An option cell, as (list, code): the workbook's own first, then the database's. */
  const option = (sheet: MasterSheetKey, row: Row, header: string, domain: Domain, c: Cell | undefined): string | null => {
    const want = text(c)?.toLowerCase();
    if (!want) return null;
    const hit = [...options, ...dbOptions.filter((o) => o.domain === domain)].find(
      (o) => o.domain === domain && [o.code, o.nameZh, o.nameEn].some((n) => n?.trim().toLowerCase() === want),
    );
    if (!hit) problems.push(`${at(sheet, row)}「${header}」:${LABELS.domain[domain]}沒有「${text(c)}」,請在「選項清單」加上`);
    return hit ? hit.code : null;
  };

  // ── charge types ──
  const chargeCodes = new Set(dbChargeTypes.map((c) => c.code));
  // One the database already has is kept as it is, so only a new one is checked.
  const newChargeTypes = data.chargeTypes
    .filter((row) => !chargeCodes.has(str(row.v.code).toUpperCase()))
    .map((row) => {
      const code = str(row.v.code).toUpperCase();
      const category = fromLabel('category', str(row.v.category));
      if (!category) problems.push(`${at('chargeTypes', row)}「類別」:「${str(row.v.category)}」不是 ${Object.values(LABELS.category).join(' / ')}`);
      if (!/^[A-Z0-9_]+$/.test(code)) problems.push(`${at('chargeTypes', row)}「代碼」:只可以用英文大楷、數字和 _`);
      return { row, code, category, account: account('chargeTypes', row, '會計科目', row.v.account) };
    });
  for (const c of newChargeTypes) chargeCodes.add(c.code);

  // ── landlords ──
  const landlordCodes = new Set(dbLandlords.map((l) => l.code));
  const landlords = data.landlords.map((row) => {
    let code = str(row.v.code);
    try {
      code = landlordCode(code);
    } catch {
      problems.push(`${at('landlords', row)}「代碼」:業主代碼要兩個英文字母,例如 WF`);
    }
    landlordCodes.add(code);
    return { row, code, account: account('landlords', row, '會計科目', row.v.account) };
  });
  /** Whether a landlord has an address to head a debit note with — the workbook's word first. */
  const hasAddress = (code: string) =>
    !!(landlords.find((l) => l.code === code) ? text(landlords.find((l) => l.code === code)!.row.v.address) : dbLandlords.find((l) => l.code === code)?.address?.trim());
  const landlord = (sheet: MasterSheetKey, row: Row, header: string, c: Cell | undefined): string | null => {
    const code = text(c)?.toUpperCase() ?? null;
    if (code && !landlordCodes.has(code)) problems.push(`${at(sheet, row)}「${header}」:沒有業主公司「${code}」`);
    return code;
  };
  const contacts = data.landlordContacts.map((row) => ({
    row,
    landlord: landlord('landlordContacts', row, '業主代碼', row.v.landlord),
    country: option('landlordContacts', row, '國家/地區', 'COUNTRY', row.v.country),
  }));

  // ── properties and their units ──
  const propertyKeys = new Set<string>();
  const propertyRows = data.properties.map((row) => {
    const key = str(row.v.code);
    if (propertyKeys.has(key)) problems.push(`${at('properties', row)}「物業編號」:「${key}」重複`);
    propertyKeys.add(key);
    const letterhead = text(row.v.letterhead) ? fromLabel('letterhead', str(row.v.letterhead)) : undefined;
    if (text(row.v.letterhead) && !letterhead) problems.push(`${at('properties', row)}「請款單信頭」:「${str(row.v.letterhead)}」不是 ${Object.values(LABELS.letterhead).join(' / ')}`);
    const owner = landlord('properties', row, '業主代碼', row.v.landlord);
    if (letterhead === 'LANDLORD' && !(owner && hasAddress(owner))) problems.push(`${at('properties', row)}「請款單信頭」:用業主公司信頭,業主公司必須有地址`);
    return {
      row,
      key,
      landlord: owner,
      category: option('properties', row, '物業類別', 'PROPERTY_CATEGORY', row.v.category),
      country: option('properties', row, '國家/地區', 'COUNTRY', row.v.country),
      letterhead,
      units: [] as string[],
    };
  });
  const propertyByKey = new Map(propertyRows.map((p) => [p.key, p]));
  for (const row of data.units) {
    const p = propertyByKey.get(str(row.v.property));
    const name = str(row.v.name);
    if (!p) problems.push(`${at('units', row)}「物業編號」:「物業」表沒有「${str(row.v.property)}」`);
    else if (p.units.includes(name)) problems.push(`${at('units', row)}「單位」:${p.key} 已經有「${name}」`);
    else p.units.push(name);
  }
  const unitKnown = (property: string, unit: string) => propertyByKey.get(property)?.units.includes(unit) ?? false;

  // ── tenants and their codes ──
  // A tenant the database already has by that name is the one meant — in a new
  // database, the seed's demo tenant, which every export of one carries.
  const sameName = (name: string) => dbTenants.find((t) => t.name.trim().toLowerCase() === name.trim().toLowerCase());
  const tenantRefs = new Map<string, { row: Row; codes: { landlord: string; code: string; account: string | null }[] }>();
  for (const row of data.tenants) {
    const ref = str(row.v.ref);
    if (tenantRefs.has(ref)) problems.push(`${at('tenants', row)}「租客參考」:「${ref}」重複`);
    const email = text(row.v.email);
    if (email && !EMAIL.test(email)) problems.push(`${at('tenants', row)}「電郵」:「${email}」不是電郵地址`);
    if ((text(row.v.address)?.length ?? 0) > 500) problems.push(`${at('tenants', row)}「地址」:超過 500 字`);
    tenantRefs.set(ref, { row, codes: [] });
  }
  const codesSeen = new Set<string>();
  for (const row of data.tenantCodes) {
    const t = tenantRefs.get(str(row.v.tenant));
    const seen = str(row.v.code).toUpperCase();
    if (codesSeen.has(seen)) problems.push(`${at('tenantCodes', row)}「租客代碼」:「${seen}」重複`);
    codesSeen.add(seen);
    if (t?.codes.some((c) => c.landlord === str(row.v.landlord).toUpperCase())) problems.push(`${at('tenantCodes', row)}:同一租客在同一業主公司只可以有一個代碼`);
    const ll = landlord('tenantCodes', row, '業主代碼', row.v.landlord);
    let code = str(row.v.code);
    if (ll) {
      try {
        code = tenantCode(code, ll);
      } catch (e) {
        problems.push(`${at('tenantCodes', row)}「租客代碼」:${e instanceof Error ? e.message : e}`);
      }
    }
    if (!t) problems.push(`${at('tenantCodes', row)}「租客參考」:「租客」表沒有「${str(row.v.tenant)}」`);
    else if (sameName(str(t.row.v.name))) problems.push(`${at('tenantCodes', row)}:系統已有租客「${str(t.row.v.name)}」,匯入不會改動它,請在系統內為它加代碼`);
    else if (ll) t.codes.push({ landlord: ll, code, account: account('tenantCodes', row, '會計科目', row.v.account) });
  }

  // ── leases, their units and their charges ──
  const leaseRows = new Map<
    string,
    {
      row: Row;
      status: 'DRAFT' | 'ACTIVE' | 'ENDED' | 'TERMINATED';
      currency: 'HKD' | 'SGD';
      leaseType: string | null;
      usage: string | null;
      units: { property: string; unit: string; group: string | null }[];
      charges: { row: Row; chargeType: string; timing: 'ADVANCE' | 'ARREARS'; proration: 'DAILY' | 'FULL_MONTH'; property: string | null; unit: string | null }[];
    }
  >();
  for (const row of data.leases) {
    const ref = str(row.v.reference);
    if (leaseRows.has(ref)) problems.push(`${at('leases', row)}「租約編號」:「${ref}」重複`);
    if (!tenantRefs.has(str(row.v.tenant))) problems.push(`${at('leases', row)}「租客參考」:「租客」表沒有「${str(row.v.tenant)}」`);
    const status = fromLabel('status', str(row.v.status));
    if (!status) problems.push(`${at('leases', row)}「狀態」:「${str(row.v.status)}」不是 ${Object.values(LABELS.status).join(' / ')}`);
    const currency = fromLabel('currency', str(row.v.currency));
    if (!currency) problems.push(`${at('leases', row)}「貨幣」:「${str(row.v.currency)}」不是 HKD / SGD`);
    if (row.v.startDate && row.v.endDate && String(row.v.endDate) < String(row.v.startDate)) problems.push(`${at('leases', row)}:結束日期早過開始日期`);
    if (!!row.v.rentFreeFrom !== !!row.v.rentFreeTo) problems.push(`${at('leases', row)}:免租開始同結束要一齊填`);
    const bank = text(row.v.bankAccount);
    if (bank && !bankId.has(bank.toLowerCase())) problems.push(`${at('leases', row)}「收款戶口」:系統沒有收款銀行戶口「${bank}」,請先在系統新增`);
    leaseRows.set(ref, {
      row,
      status: status ?? 'ACTIVE',
      currency: currency ?? 'HKD',
      leaseType: option('leases', row, '租約類型', 'LEASE_TYPE', row.v.leaseType),
      usage: option('leases', row, '租用用途', 'LEASE_USAGE', row.v.usage),
      units: [],
      charges: [],
    });
  }
  for (const [ref, l] of leaseRows) {
    const from = text(l.row.v.renewedFrom);
    if (from && (!leaseRows.has(from) || from === ref)) problems.push(`${at('leases', l.row)}「續租自」:「租約」表沒有另一份「${from}」`);
  }
  for (const row of data.leaseUnits) {
    const l = leaseRows.get(str(row.v.lease));
    const property = str(row.v.property);
    const unit = str(row.v.unit);
    if (!l) problems.push(`${at('leaseUnits', row)}「租約編號」:「租約」表沒有「${str(row.v.lease)}」`);
    else if (!unitKnown(property, unit)) problems.push(`${at('leaseUnits', row)}:「單位」表沒有 ${property}「${unit}」`);
    else if (l.units.some((u) => u.property === property && u.unit === unit)) problems.push(`${at('leaseUnits', row)}:單位重複`);
    else l.units.push({ property, unit, group: text(row.v.billingGroup) });
  }
  for (const l of leaseRows.values()) if (l.units.length === 0) problems.push(`${at('leases', l.row)}:「租約單位」表沒有這份租約的單位`);
  for (const row of data.charges) {
    const l = leaseRows.get(str(row.v.lease));
    const chargeType = str(row.v.chargeType).toUpperCase();
    if (!chargeCodes.has(chargeType)) problems.push(`${at('charges', row)}「收費類型」:沒有收費類型「${chargeType}」`);
    if (typeof row.v.amount === 'number' && row.v.amount < 0) problems.push(`${at('charges', row)}「金額」:不可以係負數`);
    const timing = text(row.v.timing) ? fromLabel('timing', str(row.v.timing)) : 'ADVANCE';
    if (!timing) problems.push(`${at('charges', row)}「預繳/後繳」:「${str(row.v.timing)}」不是 ${Object.values(LABELS.timing).join(' / ')}`);
    const proration = text(row.v.proration) ? fromLabel('proration', str(row.v.proration)) : 'DAILY';
    if (!proration) problems.push(`${at('charges', row)}「不足一月」:「${str(row.v.proration)}」不是 ${Object.values(LABELS.proration).join(' / ')}`);
    const property = text(row.v.property);
    const unit = text(row.v.unit);
    if (!l) {
      problems.push(`${at('charges', row)}「租約編號」:「租約」表沒有「${str(row.v.lease)}」`);
      continue;
    }
    if ((property || unit) && !l.units.some((u) => u.property === property && u.unit === unit)) {
      problems.push(`${at('charges', row)}「只收此單位」:${property ?? ''}「${unit ?? ''}」不是這份租約的單位`);
    }
    l.charges.push({ row, chargeType, timing: timing ?? 'ADVANCE', proration: proration ?? 'DAILY', property, unit });
  }

  if (problems.length) throw new MasterDataProblems(problems);

  const summary: ImportSummary = { created: {}, kept: [], addedAccounts: [...missingAccounts].sort() };
  const count = (k: MasterSheetKey) => (summary.created[k] = (summary.created[k] ?? 0) + 1);
  for (const o of options) {
    if (dbOptions.some((d) => d.domain === o.domain && d.code === o.code)) summary.kept.push(`${LABELS.domain[o.domain]} ${o.code}`);
  }
  for (const row of data.chargeTypes) {
    const code = str(row.v.code).toUpperCase();
    if (!newChargeTypes.some((c) => c.code === code)) summary.kept.push(`收費類型 ${code}`);
  }
  for (const t of tenantRefs.values()) if (sameName(str(t.row.v.name))) summary.kept.push(`租客 ${str(t.row.v.name)}`);
  if (opts.dryRun) return summary;

  // The chart's accounts first: charge types, landlords and tenant codes name them.
  for (const code of summary.addedAccounts) {
    accountId.set(code, (await prisma.glAccount.create({ data: { organizationId, code, name: code, type: accountTypeFor(code) } })).id);
  }

  // ── write, through the back office's own calls ──
  const permissions = (await prisma.permission.findMany({ select: { key: true } })).map((p) => p.key);
  const user: AuthUser = { id: 'master-data-import', email: '', name: 'Master data import', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions };
  const ctx = { prisma, user, organizationId } as unknown as Context;
  const call = {
    options: referenceValuesRouter.createCaller(ctx),
    chargeTypes: chargeTypesRouter.createCaller(ctx),
    landlords: landlordsRouter.createCaller(ctx),
    properties: propertiesRouter.createCaller(ctx),
    tenants: tenantsRouter.createCaller(ctx),
    leases: leasesRouter.createCaller(ctx),
  };
  /** Runs one write, naming the row when it is refused. */
  const write = async <T>(sheet: MasterSheetKey, row: Row, fn: () => Promise<T>): Promise<T> => {
    try {
      return await fn();
    } catch (e) {
      throw new MasterDataProblems([`${at(sheet, row)}:${e instanceof Error ? e.message : e}(之前的紀錄已經寫入,請用新資料庫重新匯入)`]);
    }
  };

  for (const o of options) {
    if (dbOptions.some((d) => d.domain === o.domain && d.code === o.code)) continue;
    await write('options', o.row, () =>
      call.options.create({ domain: o.domain, code: o.code, nameEn: o.nameEn, nameZh: o.nameZh, sortOrder: o.sortOrder, isActive: o.isActive }),
    );
    count('options');
  }
  const optionId = new Map(
    (await prisma.referenceValue.findMany({ where: org, select: { id: true, domain: true, code: true } })).map((o) => [`${o.domain}:${o.code}`, o.id]),
  );
  const optionRef = (domain: Domain, code: string | null) => (code ? optionId.get(`${domain}:${code}`) ?? null : null);

  for (const c of newChargeTypes) {
    await write('chargeTypes', c.row, () =>
      call.chargeTypes.create({
        code: c.code,
        nameEn: str(c.row.v.nameEn),
        nameZh: text(c.row.v.nameZh),
        category: c.category!,
        glAccountId: c.account ? accountId.get(c.account) : null,
        waivedDuringRentFree: c.row.v.waived === true,
        isActive: c.row.v.isActive !== false,
        sortOrder: Number(c.row.v.sortOrder ?? 0),
      }),
    );
    count('chargeTypes');
  }

  const landlordId = new Map(dbLandlords.map((l) => [l.code, l.id]));
  for (const l of landlords) {
    const input = {
      code: l.code,
      name: str(l.row.v.name),
      nameZh: text(l.row.v.nameZh),
      address: text(l.row.v.address),
      tel: text(l.row.v.tel),
      email: text(l.row.v.email),
      glAccountId: l.account ? accountId.get(l.account) : null,
      isActive: l.row.v.isActive !== false,
      sortOrder: Number(l.row.v.sortOrder ?? 0),
      contacts: contacts
        .filter((c) => c.landlord === l.code)
        .map((c) => ({ countryId: optionRef('COUNTRY', c.country)!, tel: text(c.row.v.tel), email: text(c.row.v.email) })),
    };
    const existing = landlordId.get(l.code);
    if (existing) await write('landlords', l.row, () => call.landlords.update({ id: existing, ...input }));
    else landlordId.set(l.code, (await write('landlords', l.row, () => call.landlords.create(input))).id);
    count('landlords');
  }

  const unitId = new Map<string, string>();
  for (const p of propertyRows) {
    const v = p.row.v;
    const { id } = await write('properties', p.row, () =>
      call.properties.create({
        name: str(v.name),
        address: text(v.address) ?? undefined,
        landlordId: p.landlord ? landlordId.get(p.landlord) : null,
        categoryId: optionRef('PROPERTY_CATEGORY', p.category),
        countryId: optionRef('COUNTRY', p.country),
        letterheadSource: p.letterhead,
        code: isPlaceholder(p.key) ? null : p.key,
        completionDate: text(v.completionDate),
        purchasePrice: amount(v.purchasePrice),
        saleCompletionDate: text(v.saleCompletionDate),
        salePrice: amount(v.salePrice),
        landLeaseTerm: text(v.landLeaseTerm),
        landLeaseCommencement: text(v.landLeaseCommencement),
        units: p.units.map((name) => ({ name })),
      }),
    );
    for (const u of await prisma.unit.findMany({ where: { propertyId: id }, select: { id: true, name: true } })) unitId.set(`${p.key}\u0000${u.name}`, u.id);
    count('properties');
    summary.created.units = (summary.created.units ?? 0) + p.units.length;
  }

  const tenantId = new Map<string, string>();
  for (const [ref, t] of tenantRefs) {
    const v = t.row.v;
    const existing = sameName(str(v.name));
    if (existing) {
      tenantId.set(ref, existing.id);
      continue;
    }
    const { id } = await write('tenants', t.row, () =>
      call.tenants.create({
        name: str(v.name),
        nameZh: text(v.nameZh) ?? undefined,
        attention: text(v.attention) ?? undefined,
        phone: text(v.phone) ?? undefined,
        email: text(v.email) ?? undefined,
        address: text(v.address) ?? undefined,
        printAddress: v.printAddress === null ? undefined : v.printAddress === true,
        printPhone: v.printPhone === null ? undefined : v.printPhone === true,
        printEmail: v.printEmail === null ? undefined : v.printEmail === true,
        codes: t.codes.map((c) => ({ landlordId: landlordId.get(c.landlord)!, code: c.code, glAccountId: c.account ? accountId.get(c.account) : null })),
      }),
    );
    tenantId.set(ref, id);
    count('tenants');
    summary.created.tenantCodes = (summary.created.tenantCodes ?? 0) + t.codes.length;
  }

  const chargeTypeId = new Map((await prisma.chargeType.findMany({ where: org, select: { id: true, code: true } })).map((c) => [c.code, c.id]));
  // A renewal points at the lease it renews, so that one is made first.
  const leaseId = new Map<string, string>();
  const pending = [...leaseRows.entries()];
  while (pending.length) {
    const i = pending.findIndex(([, l]) => !text(l.row.v.renewedFrom) || leaseId.has(str(l.row.v.renewedFrom)));
    if (i < 0) throw new MasterDataProblems([`${at('leases', pending[0][1].row)}「續租自」:續租關係形成循環`]);
    const [ref, l] = pending.splice(i, 1)[0];
    const v = l.row.v;
    const unitOf = (property: string, unit: string) => unitId.get(`${property}\u0000${unit}`)!;
    const { id } = await write('leases', l.row, () =>
      call.leases.create({
        reference: isPlaceholder(ref) ? undefined : ref,
        tenantId: tenantId.get(str(v.tenant))!,
        status: l.status,
        currency: l.currency,
        startDate: str(v.startDate),
        endDate: str(v.endDate),
        dueDayOfMonth: typeof v.dueDay === 'number' ? v.dueDay : null,
        bankAccountId: text(v.bankAccount) ? bankId.get(str(v.bankAccount).toLowerCase()) : null,
        depositMonths: typeof v.depositMonths === 'number' ? v.depositMonths : 0,
        rentFreeFrom: text(v.rentFreeFrom),
        rentFreeTo: text(v.rentFreeTo),
        leaseTypeId: optionRef('LEASE_TYPE', l.leaseType),
        usageId: optionRef('LEASE_USAGE', l.usage),
        noticeDays: typeof v.noticeDays === 'number' ? v.noticeDays : null,
        note: text(v.note),
        renewedFromId: text(v.renewedFrom) ? leaseId.get(str(v.renewedFrom)) : null,
        unitIds: l.units.map((u) => unitOf(u.property, u.unit)),
        billingGroups: Object.fromEntries(l.units.filter((u) => u.group).map((u) => [unitOf(u.property, u.unit), u.group!])),
        labels: splitList(text(v.labels)),
        chargeRules: l.charges.map((c) => ({
          chargeTypeId: chargeTypeId.get(c.chargeType)!,
          amount: (c.row.v.amount as number).toFixed(2),
          frequencyMonths: Number(c.row.v.frequencyMonths),
          timing: c.timing,
          proration: c.proration,
          firstInvoiceOnly: c.row.v.firstInvoiceOnly === true,
          unitId: c.property && c.unit ? unitOf(c.property, c.unit) : null,
          startDate: text(c.row.v.startDate),
          endDate: text(c.row.v.endDate),
          followsStandard: c.row.v.followsStandard === true,
        })),
      }),
    );
    leaseId.set(ref, id);
    count('leases');
    summary.created.leaseUnits = (summary.created.leaseUnits ?? 0) + l.units.length;
    summary.created.charges = (summary.created.charges ?? 0) + l.charges.length;
  }
  return summary;
}
