/**
 * Functional smoke: the codes the office keys into its ERP (Multiable).
 *
 *   landlord code   2 letters                                   WF
 *   tenant code     landlord code + 4 letters/digits + 2 digits  WFCHAN01
 *
 * Each landlord company keeps its own customer list in the ERP, so a tenant has
 * one code per landlord it rents from, each with an account beside it. The
 * office asked for the system to suggest the code and let them change it. The
 * accounts — a landlord's, a tenant's — are picked from the chart of accounts;
 * the chart itself, and a charge's account, are chart-of-accounts-smoke's.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/erp-codes-smoke.ts
 */
import 'reflect-metadata';
import { PrismaService } from '../src/prisma/prisma.service';
import { landlordsRouter } from '../src/trpc/routers/landlords.router';
import { tenantsRouter } from '../src/trpc/routers/tenants.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();

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-ERP-ORG';
const OTHER_ORG = 'ZZ-ERP-OTHER';

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

const landlordFields = { name: 'ZZ Well Faith', isActive: true, sortOrder: 0 };

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ ERP codes org' } })).id;
  const otherId = (await prisma.organization.create({ data: { code: OTHER_ORG, name: 'ZZ ERP other org' } })).id;
  const landlords = landlordsRouter.createCaller(staffCtx(orgId));
  const tenants = tenantsRouter.createCaller(staffCtx(orgId));
  const account = (organizationId: string, code: string, name: string) =>
    prisma.glAccount.create({ data: { organizationId, code, name, type: 'ASSET' } });
  const wfAcct = await account(orgId, '1800-32-0000', 'WELL FAITH INTERNATIONAL ENTERPRISES LTD');
  const debtors = await account(orgId, '1200-01-0000', '應收賬項 (Accounts Receivable)');
  const foreignAcct = await account(otherId, '1800-31-0000', 'ZZ Foreign');

  console.log('A. A landlord code is two letters');
  const wf = await landlords.create({ ...landlordFields, code: ' wf ', glAccountId: wfAcct.id });
  const wfRow = await landlords.get({ id: wf.id });
  ck('A1 typed in lower case, stored upper', wfRow.code === 'WF', `got ${wfRow.code}`);
  for (const bad of ['WFX', 'W1', 'W', '1F']) {
    const msg = await refused(() => landlords.create({ ...landlordFields, code: bad }));
    ck(`A2 "${bad}" is refused, saying why`, msg.includes('2 letters'), `got "${msg}"`);
  }
  ck('A3 nor can an existing one be renamed to three', (await refused(() => landlords.update({ id: wf.id, ...landlordFields, code: 'WFF' }))).includes('2 letters'));
  const lf = await landlords.create({ ...landlordFields, name: 'ZZ Lucky Forever', code: 'LF' });

  console.log('\nB. A landlord\'s account is picked from the chart');
  ck('B1 kept, and read back with its code and name', wfRow.glAccountId === wfAcct.id && wfRow.account?.code === '1800-32-0000', `got ${JSON.stringify(wfRow.account)}`);
  const foreignPick = await refused(() => landlords.update({ id: wf.id, ...landlordFields, code: 'WF', glAccountId: foreignAcct.id }));
  ck('B2 another organisation\'s account is not ours to name', foreignPick.includes('Account not found'), `got "${foreignPick}"`);
  await prisma.glAccount.update({ where: { id: wfAcct.id }, data: { isActive: false } });
  const kept = await refused(() => landlords.update({ id: wf.id, ...landlordFields, code: 'WF', glAccountId: wfAcct.id }));
  ck('B3 an account retired since it was picked stays on the record', kept === '', `got "${kept}"`);
  const lfRetired = await refused(() => landlords.create({ ...landlordFields, name: 'ZZ Retired Pick', code: 'RP', glAccountId: wfAcct.id }));
  ck('B4 but a retired account is not picked anew', lfRetired.includes('This account is inactive'), `got "${lfRetired}"`);
  await landlords.update({ id: wf.id, ...landlordFields, code: 'WF', glAccountId: '' });
  ck('B5 blank clears it', (await landlords.get({ id: wf.id })).glAccountId === null);

  console.log('\nC. A tenant has a code per landlord, suggested and editable');
  const s1 = await tenants.suggestCode({ landlordId: wf.id, name: 'Chan Tai Man Trading Ltd' });
  ck('C1 suggested from the landlord code, the name and 01', s1.code === 'WFCHAN01', `got ${JSON.stringify(s1)}`);
  const chan = await tenants.create({ name: 'Chan Tai Man Trading Ltd', codes: [{ landlordId: wf.id, code: 'wfchan01', glAccountId: debtors.id }] });
  const listed = (await tenants.list()).find((t) => t.id === chan.id);
  const expected = [{ landlordId: wf.id, landlordCode: 'WF', code: 'WFCHAN01', glAccountId: debtors.id, account: { code: '1200-01-0000', name: debtors.name } }];
  ck('C2 stored upper-case, with its account and landlord', JSON.stringify(listed?.codes) === JSON.stringify(expected), `got ${JSON.stringify(listed?.codes)}`);
  const s2 = await tenants.suggestCode({ landlordId: wf.id, name: 'Chan & Sons' });
  ck('C3 the next Chan under WF is suggested 02', s2.code === 'WFCHAN02', `got ${JSON.stringify(s2)}`);
  const sZh = await tenants.suggestCode({ landlordId: wf.id, name: '陳大文' });
  ck('C4 a Chinese-only name leaves only the landlord code to start from', sZh.stem === 'WF' && sZh.code === null, `got ${JSON.stringify(sZh)}`);
  const sShort = await tenants.suggestCode({ landlordId: wf.id, name: 'Ng' });
  ck('C5 a name of under four letters leaves it to be finished', sShort.stem === 'WFNG' && sShort.code === null, `got ${JSON.stringify(sShort)}`);

  await tenants.update({
    id: chan.id, name: 'Chan Tai Man Trading Ltd',
    codes: [{ landlordId: wf.id, code: 'WFCHAN01', glAccountId: debtors.id }, { landlordId: lf.id, code: 'LFCHAN01' }],
  });
  const both = (await tenants.list()).find((t) => t.id === chan.id)?.codes.map((c) => c.code);
  ck('C6 renting from a second company gives a second code', JSON.stringify(both) === JSON.stringify(['LFCHAN01', 'WFCHAN01']), `got ${JSON.stringify(both)}`);
  await tenants.update({ id: chan.id, name: 'Chan Tai Man Trading Ltd' });
  ck('C7 an edit that does not mention codes leaves them', (await tenants.list()).find((t) => t.id === chan.id)?.codes.length === 2);

  console.log('\nD. What a tenant code is refused for');
  const other = await tenants.create({ name: 'Wong Kee' });
  const cases: [string, () => Promise<unknown>, string][] = [
    ['D1 not starting with its landlord’s code', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'LFWONG01' }] }), "must start with its landlord's code WF"],
    ['D2 seven characters', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFWONG1' }] }), '8 characters'],
    ['D3 a symbol in the name part', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFWO&G01' }] }), '8 characters'],
    ['D4 letters where the number goes', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFWONGAB' }] }), '8 characters'],
    ['D5 someone else’s code', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFCHAN01' }] }), 'Tenant code WFCHAN01 is already in use'],
    ['D6 two codes under one landlord', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFWONG01' }, { landlordId: wf.id, code: 'WFWONG02' }] }), 'only one code per landlord'],
    ['D7 an account not in our chart', () => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFWONG01', glAccountId: foreignAcct.id }] }), 'Account not found'],
  ];
  for (const [name, fn, says] of cases) {
    const msg = await refused(fn);
    ck(name, msg.includes(says), `got "${msg}"`);
  }
  ck('D8 and nothing was written by any of them', (await prisma.tenantCode.count({ where: { tenantId: other.id } })) === 0);
  const foreignLandlord = await prisma.landlord.create({ data: { organizationId: otherId, code: 'WF', name: 'ZZ Foreign' } });
  const foreign = await refused(() => tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: foreignLandlord.id, code: 'WFWONG01' }] }));
  ck('D9 another organisation’s landlord is not ours to name', foreign.includes('Landlord not found'), `got "${foreign}"`);
  const createBad = await refused(() => tenants.create({ name: 'Lam Bad', codes: [{ landlordId: wf.id, code: 'WFLAM' }] }));
  ck('D10 a refused code on create leaves no tenant behind', createBad.includes('8 characters') && (await prisma.tenant.count({ where: { organizationId: orgId, name: 'Lam Bad' } })) === 0);

  console.log('\nE. Clearing');
  await tenants.update({ id: chan.id, name: 'Chan Tai Man Trading Ltd', codes: [] });
  ck('E1 an empty set clears the codes', (await prisma.tenantCode.count({ where: { tenantId: chan.id } })) === 0);
  const freed = await tenants.update({ id: other.id, name: 'Wong Kee', codes: [{ landlordId: wf.id, code: 'WFCHAN01' }] }).then(() => '', (e: Error) => e.message);
  ck('E2 and a cleared code is free for another tenant', freed === '', `got "${freed}"`);
}

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;
    await prisma.tenantCode.deleteMany({ where: { organizationId: org.id } });
    await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
    await prisma.landlord.deleteMany({ where: { organizationId: org.id } });
    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); });
