/**
 * Functional smoke: the master-data workbook, out and back in.
 *
 * The office keyed its standing records in once and does not want to again:
 * what the back office exports must load into a new database and come out the
 * same. So this builds one organisation's worth of everything the workbook
 * carries — option values, a charge type of its own, a landlord with a contact
 * abroad, a property under its landlord's letterhead and one with no number, a
 * tenant with a code, leases with a billing group, a charge on one unit, a
 * rent-free window, labels and a renewal — exports it, removes it, loads the
 * file into an empty organisation, and exports that. The two must be the same,
 * row for row, except the lease whose number was left for the system to give.
 *
 * And the guards: a database already holding records is refused; a file with
 * mistakes is refused whole, every mistake named, nothing written; a check
 * run writes nothing.
 *
 * Standalone, self-cleaning: two ZZ organisations, purged at each end.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/master-data-smoke.ts
 */
import 'reflect-metadata';
import { PrismaClient } from '@prisma/client';
import { readXlsxSheets } from '../src/common/xlsx-read';
import { writeXlsxBytes } from '../src/common/xlsx-write';
import { masterDataRows, masterDataSheets, type MasterRows } from '../src/master-data/master-data.export';
import { MasterDataProblems, importMasterData, parseMasterWorkbook } from '../src/master-data/master-data.import';
import { MASTER_SHEETS } from '../src/master-data/master-data.workbook';

const prisma = new PrismaClient();
let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function problemsOf(fn: () => Promise<unknown>): Promise<string[]> {
  try { await fn(); return []; } catch (e) { return e instanceof MasterDataProblems ? e.problems : [`(not a workbook problem) ${e instanceof Error ? e.message : e}`]; }
}

const ORG_A = 'ZZ-MDA';
const ORG_B = 'ZZ-MDB';
const ACCOUNTS: [string, string, 'ASSET' | 'INCOME'][] = [['7120-01-0000', 'Rental income', 'INCOME'], ['1810-99-0000', 'ZZ Alpha current a/c', 'ASSET']];

/** What both organisations need before a workbook names it: the chart's
 *  accounts and the collection account, which the workbook does not carry. */
async function baseOrg(code: string, leasePrefix: string) {
  const org = await prisma.organization.create({ data: { code, name: `ZZ master data ${code}` } });
  for (const [c, name, type] of ACCOUNTS) await prisma.glAccount.create({ data: { organizationId: org.id, code: c, name, type } });
  const bank = await prisma.bankAccount.create({ data: { organizationId: org.id, name: 'ZZ Collection', bankName: 'ZZ Bank', accountName: 'ZZ', accountNumber: '000-1' } });
  await prisma.numberSequence.create({ data: { organizationId: org.id, docType: 'LEASE', prefix: leasePrefix, padding: 4 } });
  return { orgId: org.id, bankId: bank.id };
}

async function main() {
  await purge();

  // ── organisation A, keyed in by hand ──
  const { orgId: a, bankId } = await baseOrg(ORG_A, 'ZZMDA-');
  const acct = async (code: string) => (await prisma.glAccount.findFirstOrThrow({ where: { organizationId: a, code } })).id;
  const opt = (domain: 'COUNTRY' | 'LEASE_USAGE' | 'PROPERTY_CATEGORY' | 'LEASE_TYPE', code: string, nameEn: string, nameZh: string, sortOrder = 0) =>
    prisma.referenceValue.create({ data: { organizationId: a, domain, code, nameEn, nameZh, sortOrder } });
  const sg = await opt('COUNTRY', 'SG', 'Singapore', '新加坡', 1);
  await opt('COUNTRY', 'HK', 'Hong Kong', '香港');
  const retail = await opt('LEASE_USAGE', 'RETAIL', 'Retail Shop', '商舖');
  const commercial = await opt('PROPERTY_CATEGORY', 'COMMERCIAL', 'Commercial', '商業');
  const fixed = await opt('LEASE_TYPE', 'FIXED_TERM', 'Fixed Term', '固定租期');
  const rent = await prisma.chargeType.create({ data: { organizationId: a, code: 'RENT', nameEn: 'Rent', nameZh: '租金', category: 'RECURRING', glAccountId: await acct('7120-01-0000'), isSystem: true, waivedDuringRentFree: true } });
  const ac = await prisma.chargeType.create({ data: { organizationId: a, code: 'ZZ_AC_FEE', nameEn: 'Air-conditioning Charges', nameZh: '冷氣費', category: 'RECURRING', sortOrder: 3 } });
  const alpha = await prisma.landlord.create({
    data: { organizationId: a, code: 'ZA', name: 'ZZ Alpha Limited', nameZh: 'ZZ 阿爾法', address: '1 Smoke Road', tel: '2111 0000', glAccountId: await acct('1810-99-0000'), contacts: { create: [{ countryId: sg.id, tel: '+65 6000 0000', email: 'sg@zz.local' }] } },
  });
  const beta = await prisma.landlord.create({ data: { organizationId: a, code: 'ZB', name: 'ZZ Beta Limited', isActive: false, sortOrder: 2 } });
  const p1 = await prisma.property.create({
    data: {
      organizationId: a, code: 'ZZMD-P1', name: 'ZZ Smoke Plaza', address: '1 Smoke Road\nNorth Point', landlordId: alpha.id, categoryId: commercial.id, countryId: sg.id,
      letterheadSource: 'LANDLORD', completionDate: new Date('2020-05-01'), purchasePrice: '12345678.90', landLeaseTerm: '99 years', landLeaseCommencement: new Date('1960-01-01'),
      units: { create: [{ name: 'G/F Shop 1' }, { name: '1/F' }] },
    },
    include: { units: true },
  });
  const p2 = await prisma.property.create({ data: { organizationId: a, name: 'ZZ Beta House', landlordId: beta.id, units: { create: [{ name: 'Flat A' }] } }, include: { units: true } });
  const [shop, first] = p1.units;
  const tAlpha = await prisma.tenant.create({
    data: {
      organizationId: a, name: 'ZZ Shopkeeper Limited', nameZh: 'ZZ 店主', attention: 'Mr Chan', phone: '9000 0000', email: 'shop@zz.local', address: 'Shop 1\nSmoke Road', printEmail: false,
      codes: { create: [{ organizationId: a, landlordId: alpha.id, code: 'ZASHOP01' }] },
    },
  });
  const tBeta = await prisma.tenant.create({ data: { organizationId: a, name: 'ZZ Resident' } });
  const label = await prisma.leaseLabel.create({ data: { organizationId: a, name: 'ZZ M Shop' } });
  const l1 = await prisma.lease.create({
    data: {
      organizationId: a, reference: 'ZZMDA-0001', tenantId: tAlpha.id, status: 'ACTIVE', currency: 'SGD', startDate: new Date('2026-04-01'), endDate: new Date('2028-03-31'),
      dueDayOfMonth: 5, bankAccountId: bankId, depositMonths: 2, rentFreeFrom: new Date('2026-04-01'), rentFreeTo: new Date('2026-04-30'), leaseTypeId: fixed.id, usageId: retail.id, noticeDays: 90,
      note: '代號 ZZ\n管理處 2111 0000',
      units: { create: [{ unitId: shop.id }, { unitId: first.id, billingGroup: 'B' }] },
      chargeRules: { create: [
        { chargeTypeId: rent.id, amount: '65000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'DAILY', sortOrder: 0 },
        { chargeTypeId: ac.id, amount: '3016.67', frequencyMonths: 3, timing: 'ARREARS', proration: 'FULL_MONTH', unitId: first.id, startDate: new Date('2026-06-01'), endDate: new Date('2027-05-31'), sortOrder: 1 },
      ] },
      labels: { create: [{ labelId: label.id }] },
    },
  });
  await prisma.lease.create({
    data: { organizationId: a, reference: 'ZZMDA-0002', tenantId: tBeta.id, status: 'ENDED', currency: 'HKD', startDate: new Date('2024-01-01'), endDate: new Date('2025-12-31'), units: { create: [{ unitId: p2.units[0].id }] },
      chargeRules: { create: [{ chargeTypeId: rent.id, amount: '11000', frequencyMonths: 1, sortOrder: 0 }] } },
  });
  await prisma.lease.create({
    data: { organizationId: a, reference: 'ZZMDA-0003', tenantId: tAlpha.id, status: 'DRAFT', currency: 'SGD', startDate: new Date('2028-04-01'), endDate: new Date('2030-03-31'), renewedFromId: l1.id,
      units: { create: [{ unitId: shop.id }] }, chargeRules: { create: [{ chargeTypeId: rent.id, amount: '70000', frequencyMonths: 1, sortOrder: 0 }] } },
  });

  console.log('E. Exported');
  const rowsA = await masterDataRows(prisma, a);
  const bytes = writeXlsxBytes(masterDataSheets(rowsA));
  const { data, problems } = parseMasterWorkbook(readXlsxSheets(bytes));
  ck('E1 the workbook reads back with no problems', problems.length === 0, problems.join(' | '));
  ck('E2 one row per record', data.leases.length === 3 && data.leaseUnits.length === 4 && data.charges.length === 4 && data.properties.length === 2 && data.units.length === 3 && data.tenants.length === 2 && data.tenantCodes.length === 1,
    JSON.stringify(Object.fromEntries(MASTER_SHEETS.map((s) => [s.key, data[s.key].length]))));
  ck('E3 the property with no number gets a placeholder its units and lease point at',
    rowsA.properties.some((p) => p.code === '*P001') && rowsA.units.some((u) => u.property === '*P001') && rowsA.leaseUnits.some((u) => u.property === '*P001'), JSON.stringify(rowsA.properties.map((p) => p.code)));
  ck('E4 dates, money and yes/no as the office reads them',
    rowsA.leases[0].startDate === '2026-04-01' && rowsA.charges.find((c) => c.chargeType === 'ZZ_AC_FEE')?.amount === '3016.67' && rowsA.tenants.find((t) => t.name === 'ZZ Shopkeeper Limited')?.printEmail === false);

  console.log('\nG. Guards');
  const intoA = await problemsOf(() => importMasterData(prisma, a, data));
  ck('G1 a database that already has records is refused', intoA.length === 1 && intoA[0].includes('只可以匯入未有物業和租約的新資料庫'), intoA.join(' | '));
  await purgeOrg(ORG_A);
  const { orgId: b } = await baseOrg(ORG_B, 'ZZMDB-');
  const broken = structuredClone(data);
  broken.leases[0].v.tenant = 'T999';
  broken.charges[0].v.chargeType = 'NOPE';
  broken.landlords[0].v.account = '1810-00';
  const wrong = await problemsOf(() => importMasterData(prisma, b, broken));
  ck('G2 a file with mistakes is refused, each named by sheet and row',
    wrong.length === 3 && wrong.some((p) => p.includes('「租約」第 2 行「租客參考」')) && wrong.some((p) => p.includes('沒有收費類型「NOPE」')) && wrong.some((p) => p.includes('科目表沒有「1810-00」')), wrong.join(' | '));
  ck('G3 …and nothing of it written', (await prisma.landlord.count({ where: { organizationId: b } })) === 0 && (await prisma.referenceValue.count({ where: { organizationId: b } })) === 0);
  await importMasterData(prisma, b, data, { dryRun: true });
  ck('G4 a check run writes nothing', (await prisma.chargeType.count({ where: { organizationId: b } })) === 0);

  console.log('\nR. Loaded into a new organisation, and exported again');
  // The ended lease is loaded as one keyed in without a number would be.
  const loaded = structuredClone(data);
  for (const sheet of ['leases', 'leaseUnits', 'charges'] as const) {
    for (const row of loaded[sheet]) for (const k of ['reference', 'lease']) if (row.v[k] === 'ZZMDA-0002') row.v[k] = '*L1';
  }
  // A tenant B already has — as a new database has the seed's demo tenant.
  const resident = await prisma.tenant.create({ data: { organizationId: b, name: 'ZZ Resident' } });
  // An account code B's chart does not have yet: added, named by its code.
  loaded.tenantCodes[0].v.account = '1200-77-0000';
  const summary = await importMasterData(prisma, b, loaded);
  const added = await prisma.glAccount.findFirst({ where: { organizationId: b, code: '1200-77-0000' } });
  ck('R0 an account the chart lacks is added, named by its code, and the code points at it',
    summary.addedAccounts.join() === '1200-77-0000' && added?.name === '1200-77-0000' && added.type === 'ASSET'
      && (await prisma.tenantCode.count({ where: { organizationId: b, glAccountId: added.id } })) === 1, JSON.stringify(summary.addedAccounts));
  ck('R1 everything made', summary.created.leases === 3 && summary.created.properties === 2 && summary.created.units === 3 && summary.created.tenants === 1 && summary.created.charges === 4 && summary.created.chargeTypes === 2 && summary.created.options === 5,
    JSON.stringify(summary.created));
  const rowsB = await masterDataRows(prisma, b);
  const given = rowsB.leases.find((l) => l.tenant === rowsA.leases.find((x) => x.reference === 'ZZMDA-0002')!.tenant)?.reference;
  ck('R2 the lease left without a number is numbered by the sequence', given === 'ZZMDB-0001', String(given));
  const expected: MasterRows = JSON.parse(JSON.stringify(rowsA).replaceAll('ZZMDA-0002', String(given)));
  expected.tenantCodes[0].account = '1200-77-0000';
  for (const s of MASTER_SHEETS) {
    const want = JSON.stringify(sorted(expected[s.key]));
    const got = JSON.stringify(sorted(rowsB[s.key]));
    ck(`R3 「${s.name}」 the same, row for row`, want === got, `\n      want ${want}\n      got  ${got}`);
  }
  const renewal = await prisma.lease.findFirstOrThrow({ where: { organizationId: b, reference: 'ZZMDA-0003' }, include: { renewedFrom: true } });
  ck('R4 the renewal points at the lease it renews', renewal.renewedFrom?.reference === 'ZZMDA-0001');
  ck('R5 a tenant the database already has is used, not made twice',
    (await prisma.tenant.count({ where: { organizationId: b, name: 'ZZ Resident' } })) === 1
      && (await prisma.lease.count({ where: { organizationId: b, tenantId: resident.id } })) === 1 && summary.kept.includes('租客 ZZ Resident'));
}

const sorted = (rows: Record<string, unknown>[]) => rows.map((r) => JSON.stringify(r)).sort();

async function purgeOrg(code: string) {
  const org = await prisma.organization.findUnique({ where: { code }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  await prisma.lease.updateMany({ where, data: { renewedFromId: null } });
  await prisma.lease.deleteMany({ where });
  await prisma.leaseLabel.deleteMany({ where });
  await prisma.tenant.deleteMany({ where });
  const props = (await prisma.property.findMany({ where, select: { id: true } })).map((p) => p.id);
  await prisma.unit.deleteMany({ where: { propertyId: { in: props } } });
  await prisma.property.deleteMany({ where });
  await prisma.landlord.deleteMany({ where });
  await prisma.chargeType.deleteMany({ where });
  await prisma.referenceValue.deleteMany({ where });
  await prisma.bankAccount.deleteMany({ where });
  await prisma.glAccount.deleteMany({ where });
  await prisma.numberSequence.deleteMany({ where });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function purge() {
  await purgeOrg(ORG_A);
  await purgeOrg(ORG_B);
}

main()
  .catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); })
  .finally(async () => {
    try { await purge(); console.log('\nCleanup: OK'); } catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
    await prisma.$disconnect();
    console.log(`\n==== ${pass} passed, ${fail} failed ====`);
    process.exit(fail > 0 ? 1 : 0);
  });
