/**
 * Loads a master-data workbook — the Excel file Settings → Master data exports
 * (src/master-data) — into a new database: option lists, charge types,
 * landlord companies, properties and units, tenants and their codes, leases
 * with their units and charges.
 *
 * Only into an organisation with no properties or leases yet; the
 * whole file is checked first, and nothing is written while anything in it is
 * wrong. The database needs the collection bank accounts its leases name. An
 * account code the chart does not have yet is added, named by its code, as the
 * landlord import does; importing the ERP's chart afterwards names it.
 *
 * Run: cd apps/api && npm run import:master-data -- <file.xlsx> [--check] [--org <code>]
 *   --check   check the file against the database and write nothing
 *   --org     the organisation's code, when the database holds more than one
 */
import { readFileSync } from 'node:fs';
import { PrismaClient } from '@prisma/client';
import { readXlsxSheets } from '../src/common/xlsx-read';
import { MasterDataProblems, importMasterData, parseMasterWorkbook } from '../src/master-data/master-data.import';
import { MASTER_SHEETS } from '../src/master-data/master-data.workbook';

async function main(): Promise<number> {
  const args = process.argv.slice(2);
  const file = args.find((a) => !a.startsWith('--') && args[args.indexOf(a) - 1] !== '--org');
  const dryRun = args.includes('--check');
  const orgCode = args.includes('--org') ? args[args.indexOf('--org') + 1] : undefined;
  if (!file) {
    console.error('Usage: npm run import:master-data -- <file.xlsx> [--check] [--org <code>]');
    return 2;
  }

  const { data, problems } = parseMasterWorkbook(readXlsxSheets(readFileSync(file)));
  if (problems.length) return report(problems);

  const prisma = new PrismaClient();
  try {
    const orgs = await prisma.organization.findMany({ where: { deletedAt: null, ...(orgCode ? { code: orgCode } : {}) }, select: { id: true, code: true, name: true } });
    if (orgs.length !== 1) {
      console.error(orgs.length ? `More than one organisation (${orgs.map((o) => o.code).join(', ')}): name one with --org.` : 'No such organisation.');
      return 2;
    }
    console.log(`${dryRun ? 'Checking' : 'Importing'} ${file} into ${orgs[0].name} (${orgs[0].code})`);
    const summary = await importMasterData(prisma, orgs[0].id, data, { dryRun });
    for (const def of MASTER_SHEETS) {
      const n = dryRun ? data[def.key].length : summary.created[def.key] ?? 0;
      if (n) console.log(`  ${def.name.padEnd(8, '　')} ${n}`);
    }
    if (summary.kept.length) console.log(`  already there, left as they are: ${summary.kept.join(', ')}`);
    if (summary.addedAccounts.length) console.log(`  ${dryRun ? 'would add' : 'added'} to the chart, named by code: ${summary.addedAccounts.join(', ')}`);
    console.log(dryRun ? 'OK — nothing written (--check).' : 'Done.');
    return 0;
  } catch (e) {
    if (e instanceof MasterDataProblems) return report(e.problems);
    throw e;
  } finally {
    await prisma.$disconnect();
  }
}

function report(problems: string[]): number {
  console.error(`Not imported — ${problems.length} problem(s):`);
  for (const p of problems) console.error(`  · ${p}`);
  return 1;
}

main().then(
  (code) => process.exit(code),
  (e) => {
    console.error(e);
    process.exit(1);
  },
);
