/**
 * Functional smoke: the chart of accounts.
 *
 * The office imports into its ERP (Multiable) from Excel, keyed by the ERP's
 * account codes, and saw that the trial balance's "Account" is the same thing:
 * a charge's GL account and its account code were one account named twice. So
 * the ledger's accounts are the office's ERP chart. It is edited on one page,
 * imported from the ERP's export, and every account the office names — a
 * charge's, a landlord's, a tenant's — is picked from it.
 *
 * What has to hold, and is asserted: the system finds its own accounts by role,
 * so giving one its ERP code changes nothing it posts; those accounts keep
 * their type and cannot be retired; a charge names one account, a deposit
 * charge the security deposits account and no other charge any system account;
 * an account is deleted only while nothing touches it; the ERP's export adds
 * and renames without disturbing what the office set; and every account with a
 * balance stays in the trial balance, active or not.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/chart-of-accounts-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import type { Prisma } from '@prisma/client';
import { ApprovalService } from '../src/approvals/approval.service';
import { invoiceArState } from '../src/billing/invoice-ar';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { systemAccount } from '../src/ledger/system-accounts';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import { chargeTypesRouter } from '../src/trpc/routers/charge-types.router';
import { chartOfAccountsRouter } from '../src/trpc/routers/chart-of-accounts.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const ledger = new LedgerService();
const billing = new BillingService(prisma, ledger, new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
const reports = new ReportsService(prisma);
const tx = prisma as unknown as Prisma.TransactionClient;

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const ORG_CODE = 'ZZ-COA-ORG';
const OTHER_ORG = 'ZZ-COA-OTHER';

function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-coa-staff', email: 'zz-coa@rms.local', name: 'ZZ COA', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: ['gl-account.read', 'gl-account.create', 'gl-account.update', 'gl-account.delete', 'charge-type.read', 'charge-type.create', 'charge-type.update'],
  };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Chart of accounts org' } })).id;
  const otherId = (await prisma.organization.create({ data: { code: OTHER_ORG, name: 'ZZ Chart other org' } })).id;
  const chart = chartOfAccountsRouter.createCaller(staffCtx(orgId));
  const chargeTypes = chargeTypesRouter.createCaller(staffCtx(orgId));
  const account = async (id: string) => prisma.glAccount.findUniqueOrThrow({ where: { id } });

  // The system's own accounts, on the codes they had before the chart.
  const sys: Record<string, string> = {};
  for (const [code, name, type, role] of [
    ['1000', 'Bank', 'ASSET', 'BANK'], ['1100', 'Accounts Receivable', 'ASSET', 'RECEIVABLE'], ['2300', 'Deposits Held', 'LIABILITY', 'DEPOSITS_HELD'],
    ['2350', 'Tenant Credit', 'LIABILITY', 'TENANT_CREDIT'],
  ] as const) {
    sys[role] = (await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type, role } })).id;
  }

  console.log('A. The chart: an account is a code in the ERP\'s shape and a name');
  const rent = await chart.create({ code: ' 7120-01-0000 ', name: '租務收入(Rental Income)' });
  ck('A1 added, typed by the ERP\'s numbering (7 is income)', (await account(rent.id)).type === 'INCOME' && (await account(rent.id)).code === '7120-01-0000');
  ck('A2 another shape is refused, saying the shape', (await refused(() => chart.create({ code: '7120010000', name: 'x' }))).includes('1234-56-7890'));
  ck('A3 a code already in the chart is refused, naming it', (await refused(() => chart.create({ code: '7120-01-0000', name: 'x' }))).includes('An account with code 7120-01-0000 already exists'));
  const spare = await chart.create({ code: '7120-02-0000', name: 'Equipment Rental Income' });
  await chart.update({ id: spare.id, name: '租機收入(Equipment Rental Income)', code: '7120-09-0000' });
  ck('A4 renamed and recoded', (await account(spare.id)).name === '租機收入(Equipment Rental Income)' && (await account(spare.id)).code === '7120-09-0000');
  ck('A5 but not onto a code another account has', (await refused(() => chart.update({ id: spare.id, code: '7120-01-0000' }))).includes('already exists'));

  console.log('\nB. The system finds its own accounts by role, whatever their code');
  await chart.update({ id: sys.RECEIVABLE, code: '1200-01-0000', name: '應收賬項 (Accounts Receivable)' });
  ck('B1 receivables take the ERP\'s code', (await account(sys.RECEIVABLE)).code === '1200-01-0000');
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZCOA-', padding: 6 } });
  const rentCt = await chargeTypes.create({ code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: rent.id });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ COA Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ COA Property', units: { create: [{ name: 'A' }] } }, include: { units: true } });
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: 'ZZ-COA-L1', tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
      startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0, units: { create: [{ unitId: property.units[0].id }] },
      chargeRules: { create: [{ chargeTypeId: rentCt.id, amount: '1000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
    },
  });
  const draft = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period: '2020-01' });
  const note = await billing.issue({ organizationId: orgId, invoiceId: draft.id });
  ck('B2 a note issued after it posts to that same account', (await invoiceArState(tx, orgId, note.id)).outstanding.toFixed(2) === '1000.00'
    && (await prisma.journalLine.count({ where: { accountId: sys.RECEIVABLE, invoiceId: note.id } })) === 1);
  ck('B3 a system account keeps its type', (await refused(() => chart.update({ id: sys.RECEIVABLE, type: 'LIABILITY' }))).includes('The type of a system account cannot be changed'));
  ck('B4 and cannot be retired', (await refused(() => chart.update({ id: sys.BANK, isActive: false }))).includes('cannot be deactivated or deleted'));
  ck('B5 nor deleted', (await refused(() => chart.remove({ id: sys.TENANT_CREDIT }))).includes('cannot be deactivated or deleted'));
  const missing = await refused(() => systemAccount(prisma, orgId, 'REFUNDS_PAYABLE'));
  ck('B6 one the chart lacks is named when something needs it', missing.includes('The Refunds Payable account is not set up in the chart of accounts'), `got "${missing}"`);

  console.log('\nC. A charge posts to one account, picked from the chart');
  ck('C1 named with its code and name', (await chargeTypes.list()).find((c) => c.id === rentCt.id)?.glAccount?.code === '7120-01-0000');
  const dep = await chargeTypes.create({ code: 'RENT_DEPOSIT', nameEn: 'Rent Deposit', category: 'DEPOSIT' });
  ck('C2 a deposit charge is given the security deposits account', (await prisma.chargeType.findUniqueOrThrow({ where: { id: dep.id } })).glAccountId === sys.DEPOSITS_HELD);
  ck('C3 and cannot be pointed elsewhere', (await refused(() => chargeTypes.create({ code: 'KEY_DEPOSIT', nameEn: 'Key Deposit', category: 'DEPOSIT', glAccountId: rent.id }))).includes('A deposit charge posts to the security deposits account (2300)'));
  ck('C4 no other charge may post to a system account', (await refused(() => chargeTypes.create({ code: 'ODD', nameEn: 'Odd', category: 'ONE_OFF', glAccountId: sys.RECEIVABLE }))).includes("A system account cannot be a charge's account"));
  await chargeTypes.update({ id: dep.id, category: 'ONE_OFF', glAccountId: spare.id });
  await chargeTypes.update({ id: dep.id, category: 'DEPOSIT' });
  ck('C5 made a deposit charge again, it moves back to the deposits account', (await prisma.chargeType.findUniqueOrThrow({ where: { id: dep.id } })).glAccountId === sys.DEPOSITS_HELD);
  await chart.update({ id: spare.id, isActive: false });
  ck('C6 a retired account is not picked anew', (await refused(() => chargeTypes.create({ code: 'GEAR', nameEn: 'Gear', category: 'ONE_OFF', glAccountId: spare.id }))).includes('This account is inactive'));
  const geared = await chargeTypes.create({ code: 'GEAR', nameEn: 'Gear', category: 'ONE_OFF', glAccountId: rent.id });
  await chart.update({ id: rent.id, isActive: false });
  ck('C7 but one retired since it was picked stays', (await refused(() => chargeTypes.update({ id: geared.id, nameEn: 'Gear hire' }))) === '');
  await chart.update({ id: rent.id, isActive: true });
  const foreign = await prisma.glAccount.create({ data: { organizationId: otherId, code: '7130-01-0000', name: 'ZZ Foreign', type: 'INCOME' } });
  ck('C8 another organisation\'s account is not ours to name', (await refused(() => chargeTypes.update({ id: geared.id, glAccountId: foreign.id }))).includes('Account not found'));

  console.log('\nD. Deleting is for what nothing touches');
  const stray = await chart.create({ code: '8430-99-0000', name: 'Typo' });
  await chart.remove({ id: stray.id });
  ck('D1 an untouched account is deleted', (await prisma.glAccount.count({ where: { id: stray.id } })) === 0);
  ck('D2 one a charge names is not', (await refused(() => chart.remove({ id: rent.id }))).includes('deactivate it instead'));
  const listed = (await chart.list()).find((a) => a.id === rent.id);
  ck('D3 the chart says what touches each', listed?.postings === 1 && listed.chargeTypes === 2, JSON.stringify(listed));
  const moved = await chart.create({ code: '7120-03-0000', name: 'ZZ Rental Income (moved)' });
  await chargeTypes.update({ id: rentCt.id, glAccountId: moved.id });
  await chargeTypes.update({ id: geared.id, glAccountId: moved.id });
  ck('D4 nor one only posted to', (await refused(() => chart.remove({ id: rent.id }))).includes('deactivate it instead'));

  console.log('\nE. The ERP\'s export imports into the chart');
  const rows = [
    { code: '1200-01-0000', name: '應收賬項 (Accounts Receivable) ' },
    { code: '7120-01-0000', name: '租務收入 (Rental Income)' },
    { code: '7130-01-0000', name: '行政管理費收入 (Management Fee Income)' },
    { code: '4070-01-0000', name: "暫收費用-租務按金 (Dep rec'd in adv.-Rental Dep)" },
    { code: '6000-01-0000', name: '資本 (Share Capital)' },
    { code: '8180-99-0000', name: '維修費-其他項目 (R&M-Others)' },
    { code: '391-302-584-7', name: 'UOB Bank' },
    { code: '1300-01-0000', name: '  ' },
    { code: '7130-01-0000', name: 'twice' },
    { code: '', name: '' },
  ];
  const first = await chart.import({ rows });
  ck('E1 four added, one renamed, one already so, three reported', first.created === 4 && first.updated === 1 && first.unchanged === 1
    && JSON.stringify(first.skipped) === JSON.stringify([{ code: '391-302-584-7', reason: 'format' }, { code: '1300-01-0000', reason: 'name' }, { code: '7130-01-0000', reason: 'duplicate' }]), JSON.stringify(first));
  const byCode = async (code: string) => prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, code } });
  ck('E2 each typed by the ERP\'s numbering', (await byCode('7130-01-0000')).type === 'INCOME' && (await byCode('4070-01-0000')).type === 'LIABILITY'
    && (await byCode('6000-01-0000')).type === 'EQUITY' && (await byCode('8180-99-0000')).type === 'EXPENSE');
  const rentNow = await account(rent.id);
  ck('E3 an account it already had takes the ERP\'s description and stays the same account', rentNow.name === '租務收入 (Rental Income)' && rentNow.code === '7120-01-0000');
  ck('E4 the system\'s receivables keep their role', (await account(sys.RECEIVABLE)).role === 'RECEIVABLE');
  ck('E5 a second run changes nothing', JSON.stringify(await chart.import({ rows })) === JSON.stringify({ ...first, created: 0, updated: 0, unchanged: 6 }));
  await prisma.glAccount.update({ where: { id: rent.id }, data: { isActive: false, type: 'EQUITY' } });
  await chart.import({ rows });
  const kept = await account(rent.id);
  ck('E6 and never undoes what the office set', kept.isActive === false && kept.type === 'EQUITY');
  await prisma.glAccount.update({ where: { id: rent.id }, data: { isActive: true, type: 'INCOME' } });

  console.log('\nF. Every account with a balance is in the trial balance, active or not');
  await chart.update({ id: rent.id, isActive: false });
  const tb = (await reports.trialBalance(orgId, '2100-01-01')).groups.find((g) => g.currency === 'HKD');
  ck('F1 the retired income account is still there', tb?.rows.some((r) => r.code === '7120-01-0000' && r.credit === '1000.00') === true, JSON.stringify(tb?.rows));
  ck('F2 and the books balance', tb?.balanced === true && tb.totalDebit === '1000.00', `DR ${tb?.totalDebit} CR ${tb?.totalCredit}`);
  ck('F3 nothing at zero is listed', tb?.rows.length === 2, JSON.stringify(tb?.rows));
}

async function purge() {
  for (const code of [ORG_CODE, OTHER_ORG]) {
    const org = await prisma.organization.findUnique({ where: { code }, select: { id: true } });
    if (!org) continue;
    const where = { organizationId: org.id };
    const entries = (await prisma.journalEntry.findMany({ where, select: { id: true } })).map((e) => e.id);
    await prisma.journalLine.deleteMany({ where: { entryId: { in: entries } } });
    await prisma.journalEntry.deleteMany({ where: { id: { in: entries } } });
    const invIds = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    const leaseIds = (await prisma.lease.findMany({ where, select: { id: true } })).map((l) => l.id);
    await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
    await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
    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: { id: { in: props } } });
    await prisma.tenant.deleteMany({ where });
    await prisma.chargeType.deleteMany({ where });
    await prisma.glAccount.deleteMany({ where });
    await prisma.numberSequence.deleteMany({ where });
    await prisma.organization.delete({ where: { id: org.id } });
  }
}

async function cleanup() {
  try { await purge(); console.log('\nCleanup: OK'); }
  catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
}

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