import type { PrismaClient } from '@prisma/client';
import type { XlsxSheet } from '../common/xlsx-write';
import { LABELS, MASTER_SHEETS, labelOf, toCell, type CellValue, type MasterSheetKey } from './master-data.workbook';

export type MasterRows = Record<MasterSheetKey, Record<string, CellValue>[]>;

const day = (d: Date | null | undefined): string | null => (d ? d.toISOString().slice(0, 10) : null);
const money = (d: { toString(): string } | null | undefined): string | null => (d == null ? null : d.toString());
const OPTION_DOMAINS = Object.keys(LABELS.domain) as (keyof typeof LABELS.domain)[];

/**
 * The organisation's master data as the workbook's rows (master-data.workbook).
 * Archived records are left out, except where a lease kept still points at
 * one — a lease's tenant, its units' property, the property's landlord — so
 * every row the workbook writes can be loaded back.
 */
export async function masterDataRows(prisma: PrismaClient, organizationId: string): Promise<MasterRows> {
  const org = { organizationId };
  const [options, chargeTypes, leases] = await Promise.all([
    prisma.referenceValue.findMany({ where: { ...org, domain: { in: OPTION_DOMAINS } }, orderBy: [{ domain: 'asc' }, { sortOrder: 'asc' }, { code: 'asc' }] }),
    prisma.chargeType.findMany({ where: org, orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }], include: { glAccount: { select: { code: true } } } }),
    prisma.lease.findMany({
      where: { ...org, deletedAt: null },
      orderBy: { reference: 'asc' },
      include: {
        units: { include: { unit: { select: { id: true, name: true, propertyId: true } } } },
        chargeRules: { orderBy: { sortOrder: 'asc' }, include: { chargeType: { select: { code: true } } } },
        bankAccount: { select: { name: true } },
        labels: { include: { label: { select: { name: true } } } },
        renewedFrom: { select: { reference: true, deletedAt: true } },
      },
    }),
  ]);
  const optionName = new Map(options.map((o) => [o.id, o.nameZh || o.nameEn]));
  const named = (id: string | null) => (id ? optionName.get(id) ?? null : null);

  const leasedPropertyIds = leases.flatMap((l) => l.units.map((u) => u.unit.propertyId));
  const properties = await prisma.property.findMany({
    where: { ...org, OR: [{ deletedAt: null }, { id: { in: leasedPropertyIds } }] },
    orderBy: [{ name: 'asc' }, { code: 'asc' }, { createdAt: 'asc' }],
    include: { landlord: { select: { code: true } }, units: { orderBy: { createdAt: 'asc' } } },
  });
  const leasedUnitIds = new Set(leases.flatMap((l) => l.units.map((u) => u.unitId)));

  const tenantIds = leases.map((l) => l.tenantId);
  const tenants = await prisma.tenant.findMany({
    where: { ...org, OR: [{ deletedAt: null }, { id: { in: tenantIds } }] },
    orderBy: [{ name: 'asc' }, { createdAt: 'asc' }],
    include: { codes: { include: { landlord: { select: { code: true } }, glAccount: { select: { code: true } } }, orderBy: { code: 'asc' } } },
  });

  const landlordIds = [...properties.map((p) => p.landlordId), ...tenants.flatMap((t) => t.codes.map((c) => c.landlordId))].filter((x): x is string => !!x);
  const landlords = await prisma.landlord.findMany({
    where: { ...org, OR: [{ deletedAt: null }, { id: { in: landlordIds } }] },
    orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
    include: { glAccount: { select: { code: true } }, contacts: true },
  });

  // A property without a number gets a placeholder one, there only to tie its
  // units and leases to it.
  let unnumbered = 0;
  const propertyKey = new Map(properties.map((p) => [p.id, p.code ?? `*P${String(++unnumbered).padStart(3, '0')}`]));
  const tenantRef = new Map(tenants.map((t, i) => [t.id, `T${String(i + 1).padStart(3, '0')}`]));
  const unitOf = new Map(properties.flatMap((p) => p.units.map((u) => [u.id, { property: propertyKey.get(p.id)!, name: u.name }] as const)));

  return {
    options: options.map((o) => ({
      domain: labelOf('domain', o.domain as keyof typeof LABELS.domain),
      code: o.code,
      nameZh: o.nameZh,
      nameEn: o.nameEn,
      sortOrder: o.sortOrder,
      isActive: o.isActive,
    })),
    chargeTypes: chargeTypes.map((c) => ({
      code: c.code,
      nameEn: c.nameEn,
      nameZh: c.nameZh,
      category: labelOf('category', c.category),
      account: c.glAccount?.code ?? null,
      waived: c.waivedDuringRentFree,
      isActive: c.isActive,
      sortOrder: c.sortOrder,
    })),
    landlords: landlords.map((l) => ({
      code: l.code,
      name: l.name,
      nameZh: l.nameZh,
      address: l.address,
      tel: l.tel,
      email: l.email,
      account: l.glAccount?.code ?? null,
      isActive: l.isActive,
      sortOrder: l.sortOrder,
    })),
    landlordContacts: landlords.flatMap((l) => l.contacts.map((c) => ({ landlord: l.code, country: named(c.countryId), tel: c.tel, email: c.email }))),
    properties: properties.map((p) => ({
      code: propertyKey.get(p.id),
      name: p.name,
      address: p.address,
      landlord: p.landlord?.code ?? null,
      category: named(p.categoryId),
      country: named(p.countryId),
      letterhead: labelOf('letterhead', p.letterheadSource),
      completionDate: day(p.completionDate),
      purchasePrice: money(p.purchasePrice),
      saleCompletionDate: day(p.saleCompletionDate),
      salePrice: money(p.salePrice),
      landLeaseTerm: p.landLeaseTerm,
      landLeaseCommencement: day(p.landLeaseCommencement),
    })),
    units: properties.flatMap((p) =>
      p.units.filter((u) => !u.deletedAt || leasedUnitIds.has(u.id)).map((u) => ({ property: propertyKey.get(p.id), name: u.name })),
    ),
    tenants: tenants.map((t) => ({
      ref: tenantRef.get(t.id),
      name: t.name,
      nameZh: t.nameZh,
      attention: t.attention,
      phone: t.phone,
      email: t.email,
      address: t.address,
      printAddress: t.printAddress,
      printPhone: t.printPhone,
      printEmail: t.printEmail,
    })),
    tenantCodes: tenants.flatMap((t) =>
      t.codes.map((c) => ({ tenant: tenantRef.get(t.id), landlord: c.landlord.code, code: c.code, account: c.glAccount?.code ?? null })),
    ),
    leases: leases.map((l) => ({
      reference: l.reference,
      tenant: tenantRef.get(l.tenantId),
      status: l.status in LABELS.status ? labelOf('status', l.status as keyof typeof LABELS.status) : l.status,
      currency: l.currency,
      startDate: day(l.startDate),
      endDate: day(l.endDate),
      dueDay: l.dueDayOfMonth,
      bankAccount: l.bankAccount?.name ?? null,
      depositMonths: l.depositMonths,
      rentFreeFrom: day(l.rentFreeFrom),
      rentFreeTo: day(l.rentFreeTo),
      leaseType: named(l.leaseTypeId),
      usage: named(l.usageId),
      noticeDays: l.noticeDays,
      renewedFrom: l.renewedFrom && !l.renewedFrom.deletedAt ? l.renewedFrom.reference : null,
      labels: l.labels.map((x) => x.label.name).join('、'),
      note: l.note,
    })),
    leaseUnits: leases.flatMap((l) =>
      l.units.map((u) => ({ lease: l.reference, property: unitOf.get(u.unitId)?.property, unit: u.unit.name, billingGroup: u.billingGroup })),
    ),
    charges: leases.flatMap((l) =>
      l.chargeRules.map((r) => ({
        lease: l.reference,
        chargeType: r.chargeType.code,
        amount: r.amount.toString(),
        frequencyMonths: r.frequencyMonths,
        timing: labelOf('timing', r.timing),
        proration: labelOf('proration', r.proration),
        firstInvoiceOnly: r.firstInvoiceOnly,
        property: r.unitId ? unitOf.get(r.unitId)?.property : null,
        unit: r.unitId ? unitOf.get(r.unitId)?.name : null,
        startDate: day(r.startDate),
        endDate: day(r.endDate),
        followsStandard: r.followsStandard,
      })),
    ),
  };
}

/** What the first sheet says: how the workbook fits together, for whoever
 *  opens it to check or add to it. */
const README: string[] = [
  '主檔資料 —— 由系統匯出,可原樣匯入新資料庫(scripts/import-master-data.ts)。',
  '每張表的第一行是欄名,請勿修改;每行一筆紀錄。日期用 YYYY-MM-DD;「是/否」欄填「是」或「否」。',
  '表與表之間以編號對應:業主用「業主代碼」、物業用「物業編號」、租約用「租約編號」、收費類型用「代碼」、收款戶口用名稱、會計科目用科目編號、選項用中文名(或代碼)。',
  '租客沒有自己的編號,「租客參考」(T001…)只用於在本檔內對應,不會存入系統。',
  '新物業或新租約如未有編號,可填「*」開頭的暫代編號(例如 *P001、*L001),匯入時由系統按「單據編號」設定編號。',
  '請款單、收款、按金、讀數等交易紀錄不在本檔內。',
  `收費類型「類別」:${Object.values(LABELS.category).join(' / ')};租約「狀態」:${Object.values(LABELS.status).join(' / ')};「預繳/後繳」:${Object.values(LABELS.timing).join(' / ')};「不足一月」:${Object.values(LABELS.proration).join(' / ')};物業「請款單信頭」:${Object.values(LABELS.letterhead).join(' / ')}。`,
];

/** The rows as the workbook's sheets: the notes first, then one per kind, each
 *  headed by its column names. */
export function masterDataSheets(rows: MasterRows): XlsxSheet[] {
  return [
    { name: '說明', columns: [{ width: 140 }], rows: README.map((line, i) => ({ cells: [line], bold: i === 0 })) },
    ...MASTER_SHEETS.map((def) => ({
      name: def.name,
      columns: def.columns.map((c) => ({ width: c.width, money: c.kind === 'money' })),
      freezeRows: 1,
      rows: [
        { cells: def.columns.map((c) => c.header), bold: true },
        ...rows[def.key].map((r) => ({ cells: def.columns.map((c) => toCell(c.kind, r[c.key])) })),
      ],
    })),
  ];
}
