/**
 * The master-data workbook: the office's standing records — the option lists
 * and charge types they use, landlord companies, properties and their units,
 * tenants, and leases with their units and charges — as one Excel file, laid
 * out the way the system holds them. The back office exports it; a new database
 * is loaded from it (scripts/import-master-data.ts). This file is the single
 * description both read: what each sheet is called, its columns, and how a
 * cell is written and read back.
 *
 * Rows refer to one another by what the office already calls them: a landlord
 * by its code, a property by its property number, a lease by its lease number,
 * a charge type by its code, a bank account by its name, an account by its
 * code, an option by its Chinese name (or code). A tenant has no number of its
 * own, so the workbook gives each a reference used only to tie its rows
 * together. A property or lease number starting with `*` is the same kind of
 * placeholder: the system numbers it on import.
 *
 * Transactions — debit notes, receipts, deposits, readings — are not master
 * data and are not in it.
 */

export type CellKind = 'text' | 'int' | 'money' | 'decimal' | 'date' | 'bool';

export interface MasterColumn {
  key: string;
  header: string;
  kind?: CellKind;
  required?: boolean;
  width?: number;
}

export interface MasterSheet {
  key: MasterSheetKey;
  name: string;
  columns: MasterColumn[];
}

export type MasterSheetKey =
  | 'options'
  | 'chargeTypes'
  | 'landlords'
  | 'landlordContacts'
  | 'properties'
  | 'units'
  | 'tenants'
  | 'tenantCodes'
  | 'leases'
  | 'leaseUnits'
  | 'charges';

const col = (key: string, header: string, extra: Omit<MasterColumn, 'key' | 'header'> = {}): MasterColumn => ({ key, header, ...extra });

/** In import order: each sheet only points at sheets before it. */
export const MASTER_SHEETS: readonly MasterSheet[] = [
  {
    key: 'options',
    name: '選項清單',
    columns: [
      col('domain', '清單', { required: true, width: 12 }),
      col('code', '代碼', { required: true, width: 16 }),
      col('nameZh', '中文名', { width: 18 }),
      col('nameEn', '英文名', { required: true, width: 24 }),
      col('sortOrder', '排序', { kind: 'int', width: 8 }),
      col('isActive', '啟用', { kind: 'bool', width: 8 }),
    ],
  },
  {
    key: 'chargeTypes',
    name: '收費類型',
    columns: [
      col('code', '代碼', { required: true, width: 16 }),
      col('nameEn', '英文名', { required: true, width: 26 }),
      col('nameZh', '中文名', { width: 14 }),
      col('category', '類別', { required: true, width: 10 }),
      col('account', '會計科目', { width: 15 }),
      col('waived', '免租期豁免', { kind: 'bool', width: 10 }),
      col('isActive', '啟用', { kind: 'bool', width: 8 }),
      col('sortOrder', '排序', { kind: 'int', width: 8 }),
    ],
  },
  {
    key: 'landlords',
    name: '業主公司',
    columns: [
      col('code', '代碼', { required: true, width: 8 }),
      col('name', '英文名', { required: true, width: 40 }),
      col('nameZh', '中文名', { width: 24 }),
      col('address', '地址', { width: 40 }),
      col('tel', '電話', { width: 16 }),
      col('email', '電郵', { width: 26 }),
      col('account', '會計科目', { width: 15 }),
      col('isActive', '啟用', { kind: 'bool', width: 8 }),
      col('sortOrder', '排序', { kind: 'int', width: 8 }),
    ],
  },
  {
    key: 'landlordContacts',
    name: '業主地區聯絡',
    columns: [
      col('landlord', '業主代碼', { required: true, width: 10 }),
      col('country', '國家/地區', { required: true, width: 12 }),
      col('tel', '電話', { width: 18 }),
      col('email', '電郵', { width: 28 }),
    ],
  },
  {
    key: 'properties',
    name: '物業',
    columns: [
      col('code', '物業編號', { required: true, width: 14 }),
      col('name', '樓宇名稱', { required: true, width: 30 }),
      col('address', '地址', { width: 44 }),
      col('landlord', '業主代碼', { width: 10 }),
      col('category', '物業類別', { width: 12 }),
      col('country', '國家/地區', { width: 10 }),
      col('letterhead', '請款單信頭', { width: 12 }),
      col('completionDate', '購入成交日期', { kind: 'date', width: 13 }),
      col('purchasePrice', '購入價', { kind: 'money', width: 15 }),
      col('saleCompletionDate', '賣出成交日期', { kind: 'date', width: 13 }),
      col('salePrice', '賣出價', { kind: 'money', width: 15 }),
      col('landLeaseTerm', '地契年期', { width: 12 }),
      col('landLeaseCommencement', '地契開始日期', { kind: 'date', width: 13 }),
    ],
  },
  {
    key: 'units',
    name: '單位',
    columns: [
      col('property', '物業編號', { required: true, width: 14 }),
      col('name', '單位', { required: true, width: 36 }),
    ],
  },
  {
    key: 'tenants',
    name: '租客',
    columns: [
      col('ref', '租客參考', { required: true, width: 10 }),
      col('name', '名稱', { required: true, width: 36 }),
      col('nameZh', '中文名', { width: 20 }),
      col('attention', '聯絡人', { width: 18 }),
      col('phone', '電話', { width: 16 }),
      col('email', '電郵', { width: 28 }),
      col('address', '地址', { width: 40 }),
      col('printAddress', '請款單印地址', { kind: 'bool', width: 12 }),
      col('printPhone', '請款單印電話', { kind: 'bool', width: 12 }),
      col('printEmail', '請款單印電郵', { kind: 'bool', width: 12 }),
    ],
  },
  {
    key: 'tenantCodes',
    name: '租客代碼',
    columns: [
      col('tenant', '租客參考', { required: true, width: 10 }),
      col('landlord', '業主代碼', { required: true, width: 10 }),
      col('code', '租客代碼', { required: true, width: 12 }),
      col('account', '會計科目', { width: 15 }),
    ],
  },
  {
    key: 'leases',
    name: '租約',
    columns: [
      col('reference', '租約編號', { required: true, width: 16 }),
      col('tenant', '租客參考', { required: true, width: 10 }),
      col('status', '狀態', { required: true, width: 8 }),
      col('currency', '貨幣', { required: true, width: 7 }),
      col('startDate', '開始日期', { kind: 'date', required: true, width: 12 }),
      col('endDate', '結束日期', { kind: 'date', required: true, width: 12 }),
      col('dueDay', '每月出單日', { kind: 'int', width: 10 }),
      col('bankAccount', '收款戶口', { width: 22 }),
      col('depositMonths', '按金月數', { kind: 'int', width: 9 }),
      col('rentFreeFrom', '免租開始', { kind: 'date', width: 12 }),
      col('rentFreeTo', '免租結束', { kind: 'date', width: 12 }),
      col('leaseType', '租約類型', { width: 10 }),
      col('usage', '租用用途', { width: 10 }),
      col('noticeDays', '通知日數', { kind: 'int', width: 9 }),
      col('renewedFrom', '續租自', { width: 16 }),
      col('labels', '標籤', { width: 18 }),
      col('note', '備註', { width: 50 }),
    ],
  },
  {
    key: 'leaseUnits',
    name: '租約單位',
    columns: [
      col('lease', '租約編號', { required: true, width: 16 }),
      col('property', '物業編號', { required: true, width: 14 }),
      col('unit', '單位', { required: true, width: 36 }),
      col('billingGroup', '分單組', { width: 10 }),
    ],
  },
  {
    key: 'charges',
    name: '租約收費',
    columns: [
      col('lease', '租約編號', { required: true, width: 16 }),
      col('chargeType', '收費類型', { required: true, width: 14 }),
      col('amount', '金額', { kind: 'money', required: true, width: 14 }),
      col('frequencyMonths', '每幾個月', { kind: 'int', required: true, width: 9 }),
      col('timing', '預繳/後繳', { width: 9 }),
      col('proration', '不足一月', { width: 9 }),
      col('firstInvoiceOnly', '只收第一張', { kind: 'bool', width: 10 }),
      col('property', '單位所屬物業編號', { width: 14 }),
      col('unit', '只收此單位', { width: 24 }),
      col('startDate', '開始日期', { kind: 'date', width: 12 }),
      col('endDate', '結束日期', { kind: 'date', width: 12 }),
      col('followsStandard', '跟標準收費', { kind: 'bool', width: 10 }),
    ],
  },
];

export const sheetDef = (key: MasterSheetKey): MasterSheet => MASTER_SHEETS.find((s) => s.key === key)!;

// ── the words a cell holds for a system value ──────────────────────────────

/** Each closed list a column holds, as the back office's Chinese names it. The
 *  import takes either the name or the system's own word. */
export const LABELS = {
  domain: { LEASE_USAGE: '租用用途', PROPERTY_CATEGORY: '物業類別', LEASE_TYPE: '租約類型', COUNTRY: '國家/地區' },
  category: { RECURRING: '經常性', ONE_OFF: '一次性', DEPOSIT: '按金', UTILITY: '水電煤', ADJUSTMENT: '調整' },
  letterhead: { ORGANIZATION: '我哋公司', LANDLORD: '持有物業嗰間公司' },
  status: { DRAFT: '草稿', ACTIVE: '生效中', ENDED: '已完結', TERMINATED: '已終止' },
  timing: { ADVANCE: '預繳', ARREARS: '後繳' },
  proration: { DAILY: '按日', FULL_MONTH: '整月' },
  currency: { HKD: 'HKD', SGD: 'SGD' },
} as const;

export type LabelList = keyof typeof LABELS;

/** The system word for a cell — its label or the word itself — or undefined. */
export function fromLabel<L extends LabelList>(list: L, cell: string): keyof (typeof LABELS)[L] | undefined {
  const entries = Object.entries(LABELS[list]) as [string, string][];
  const t = cell.trim().toLowerCase();
  return entries.find(([word, label]) => word.toLowerCase() === t || label.toLowerCase() === t)?.[0] as keyof (typeof LABELS)[L] | undefined;
}

export const labelOf = <L extends LabelList>(list: L, word: keyof (typeof LABELS)[L]): string => LABELS[list][word] as string;

// ── cells ──────────────────────────────────────────────────────────────────

export type CellValue = string | number | boolean | null | undefined;

/** A value as the workbook writes it: dates as YYYY-MM-DD text, booleans as
 *  是 / 否, numbers as numbers. */
export function toCell(kind: CellKind | undefined, v: CellValue): string | number | null {
  if (v === null || v === undefined || v === '') return null;
  if (kind === 'bool') return v ? '是' : '否';
  if ((kind === 'money' || kind === 'decimal' || kind === 'int') && typeof v === 'string') return Number(v);
  return v as string | number;
}

const TRUE_WORDS = ['是', 'y', 'yes', 'true', '1', '有'];
const FALSE_WORDS = ['否', 'n', 'no', 'false', '0', '無', '冇'];

/** A cell read back, by its column's kind. Throws a sentence naming what was
 *  wrong; the caller adds where. */
export function parseCell(kind: CellKind | undefined, raw: string): string | number | boolean | null {
  const s = raw.trim();
  if (s === '') return null;
  switch (kind ?? 'text') {
    case 'text':
      return s;
    case 'bool': {
      const t = s.toLowerCase();
      if (TRUE_WORDS.includes(t)) return true;
      if (FALSE_WORDS.includes(t)) return false;
      throw new Error(`「${s}」不是 是/否`);
    }
    case 'int': {
      if (!/^-?\d+(\.0+)?$/.test(s)) throw new Error(`「${s}」不是整數`);
      return Math.trunc(Number(s));
    }
    case 'money':
    case 'decimal': {
      const n = Number(s.replace(/,/g, ''));
      if (!Number.isFinite(n)) throw new Error(`「${s}」不是數字`);
      // Excel stores 0.1 + 0.2 as 0.30000000000000004; two places is all any
      // amount or area here holds.
      return Math.round(n * 100) / 100;
    }
    case 'date':
      return parseDate(s);
  }
}

/** YYYY-MM-DD from what a date cell can hold: the workbook's own text, a date
 *  typed in Excel (stored as its serial number), or YYYY/M/D. */
export function parseDate(s: string): string {
  if (/^\d+(\.\d+)?$/.test(s)) {
    // Excel's day 1 is 1900-01-01, counting a 29 February 1900 that never was.
    const d = new Date(Date.UTC(1899, 11, 30) + Math.floor(Number(s)) * 86_400_000);
    return d.toISOString().slice(0, 10);
  }
  const m = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/.exec(s);
  if (m) {
    const iso = `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
    const d = new Date(`${iso}T00:00:00Z`);
    if (!Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === iso) return iso;
  }
  throw new Error(`「${s}」不是日期(用 YYYY-MM-DD)`);
}

/** A placeholder number: the system assigns the real one on import. */
export const isPlaceholder = (code: string): boolean => code.trim().startsWith('*');

/** Several values in one cell — a lease's labels. */
export const splitList = (s: string | null): string[] =>
  (s ?? '')
    .split(/[,，、\n]/)
    .map((x) => x.trim())
    .filter(Boolean);
