/**
 * Functional smoke: document numbers, as the office decides them.
 *
 * Two halves. The format — laid out as the ERP's: symbol, special strings,
 * company code, year, month and serial, in the office's order; where the count
 * is up to, and whether it restarts each year or month — is set on the Settings
 * page; until now only a database edit could change it. And any one debit note,
 * receipt, deposit receipt or lease can be given a number typed in as it is
 * created, blank meaning "the next in sequence". A typed number never moves the
 * sequence, and the sequence steps over one a typed number has taken, so the two
 * mix without colliding.
 *
 * With the company code in it, each landlord company keeps its own count, as
 * the ERP does (DN-WF261001, DN-AB261001); year and month are the document's
 * own; and a document of no company, or of two, is refused a number.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/numbering-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { hkDay } from '../src/common/hk-date';
import { NumberService } from '../src/common/number.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PaymentsService } from '../src/payments/payments.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { leasesRouter } from '../src/trpc/routers/leases.router';
import { numberingRouter } from '../src/trpc/routers/numbering.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const numbers = new NumberService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), numbers, new EventEmitter2(), approvals);
const payments = new PaymentsService(prisma, new LedgerService(), numbers, new EventEmitter2());
const deposits = new DepositsService(prisma, new LedgerService(), numbers, approvals);

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-NUM-ORG';
/** This month in Hong Kong, as the numbers show it: "2610". */
const YYMM = hkDay(new Date()).slice(2, 6);
const YY = YYMM.slice(0, 2);
/** Symbol + "-" + year + serial: the yearly restart as it used to look. */
const YEARLY_PARTS = ['SYMBOL', 'YEAR', 'TEXT1', 'SERIAL'] as const;
const ERP_PARTS = ['SYMBOL', 'TEXT1', 'COMPANY', 'YEAR', 'MONTH', 'SERIAL'] as const;

function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-num-staff', email: 'zz-num@rms.local', name: 'ZZ Num', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: ['setting.read', 'setting.update', 'lease.create', 'lease.read'],
  };
  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 Numbering smoke org' } })).id;
  for (const [docType, prefix] of [['INVOICE', 'DN-'], ['RECEIPT', 'RE-'], ['DEPOSIT', 'DEP-'], ['LEASE', 'L-']]) {
    await prisma.numberSequence.create({ data: { organizationId: orgId, docType, prefix, padding: 6 } });
  }
  for (const [code, name, type, role] of [['1000', 'Bank', 'ASSET', 'BANK'], ['1100', 'Accounts Receivable', 'ASSET', 'RECEIVABLE'], ['2300', 'Deposits Held', 'LIABILITY', 'DEPOSITS_HELD'], ['4000', 'Rental Income', 'INCOME', null]] as const) {
    await prisma.glAccount.create({ data: { organizationId: orgId, code, name, type, role } });
  }
  const income = await prisma.glAccount.findFirstOrThrow({ where: { organizationId: orgId, code: '4000' } });
  const rent = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RENT', nameEn: 'Rent', category: 'RECURRING', glAccountId: income.id } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Num Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Num Property', units: { create: [{ name: 'ZZ 1/F' }] } }, include: { units: true } });
  const rentedLease = (p: { id: string; units: { id: string }[] }, reference: string) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
        startDate: new Date('2020-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0, units: { create: [{ unitId: p.units[0].id }] },
        chargeRules: { create: [{ chargeTypeId: rent.id, amount: '1000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 }] },
      },
      include: { units: true },
    });
  const lease = await rentedLease(property, 'ZZ-NUM-LEASE');
  let month = 0;
  const draftOf = async (leaseId: string, period: string) => (await billing.generateDraft({ organizationId: orgId, leaseId, period })).id;
  const draft = () => draftOf(lease.id, `2020-${String(++month).padStart(2, '0')}`);
  const issue = (invoiceId: string, number?: string) => billing.issue({ organizationId: orgId, invoiceId, number });
  const numbering = numberingRouter.createCaller(staffCtx(orgId));
  const nextOf = async (docType: string) => (await numbering.list()).sequences.find((r) => r.docType === docType)?.next;
  const plain = { text1: '', text2: '', parts: ['SYMBOL', 'SERIAL'] as ('SYMBOL' | 'SERIAL')[] };
  const yearly = { text1: '-', text2: '', parts: [...YEARLY_PARTS], resetPeriod: 'YEARLY' as const };

  console.log('A. The format is the office’s to set');
  // Numbers are unique across the whole database, so another organisation's DN-000001
  // already being there moves ours on: the preview says where, it is not always 1.
  const firstNext = (await numbering.list()).sequences.map((r) => r.next);
  ck('A1 every document type is listed with what it will be numbered next', /^DN-\d{6},RE-\d{6},DEP-\d{6},L-\d{6}$/.test(firstNext.join(',')), `got ${JSON.stringify(firstNext)}`);
  await numbering.update({ docType: 'INVOICE', prefix: 'WF-DN-', padding: 4, ...yearly, counts: [{ landlordId: null, nextValue: 50 }] });
  ck('A2 symbol, a special string, the year, digits, a starting number and a yearly restart', (await nextOf('INVOICE')) === `WF-DN-${YY}-0050`, `got ${await nextOf('INVOICE')}`);
  const badPrefix = await refused(() => numbering.update({ docType: 'INVOICE', prefix: 'DN 1', padding: 4, ...yearly }));
  ck('A3 a prefix with a space is refused, saying what may go in one', badPrefix.includes('A prefix may use only'), `got "${badPrefix}"`);
  ck('A4 and leaves the format as it was', (await nextOf('INVOICE')) === `WF-DN-${YY}-0050`);
  const noYear = await refused(() => numbering.update({ docType: 'INVOICE', prefix: 'DN', padding: 4, ...plain, resetPeriod: 'YEARLY' }));
  ck('A5 a yearly restart without the year in the number is refused — next year would repeat this year', noYear === 'A yearly restart needs the year in the number', `got "${noYear}"`);
  const noMonth = await refused(() => numbering.update({ docType: 'INVOICE', prefix: 'DN', padding: 4, ...yearly, resetPeriod: 'MONTHLY' }));
  ck('A6 so is a monthly one without the month', noMonth === 'A monthly restart needs the year and the month in the number', `got "${noMonth}"`);
  const noSerial = await refused(() => numbering.update({ docType: 'INVOICE', prefix: 'DN', padding: 4, ...plain, parts: ['SYMBOL'], resetPeriod: 'NEVER' }));
  ck('A7 and a number with no serial in it', noSerial === 'A number must include its serial number', `got "${noSerial}"`);
  const badText = await refused(() => numbering.update({ docType: 'INVOICE', prefix: 'DN', padding: 4, ...yearly, text1: 'A B' }));
  ck('A8 a special string is held to the prefix’s rule', badText.includes('A special string may use only'), `got "${badText}"`);
  ck('A9 none of which touched the format', (await nextOf('INVOICE')) === `WF-DN-${YY}-0050`);

  console.log('\nB. A debit note takes the next number, or one typed for it');
  const inv1 = await draft();
  ck('B1 left blank, it gets what Settings said it would', (await issue(inv1)).number === `WF-DN-${YY}-0050`);
  ck('B2 and the count moves on', (await nextOf('INVOICE')) === `WF-DN-${YY}-0051`, `got ${await nextOf('INVOICE')}`);
  const inv2 = await draft();
  ck('B3 a typed number is used as typed, spaces around it trimmed', (await issue(inv2, '  DN-OWN-1 ')).number === 'DN-OWN-1');
  ck('B4 and does not move the count', (await nextOf('INVOICE')) === `WF-DN-${YY}-0051`, `got ${await nextOf('INVOICE')}`);
  const inv3 = await draft();
  const dup = await refused(() => issue(inv3, 'DN-OWN-1'));
  ck('B5 a number already used is refused, naming it', dup === 'Number DN-OWN-1 is already used', `got "${dup}"`);
  const malformed = await refused(() => issue(inv3, 'DN OWN 2'));
  ck('B6 so is one with a space in it', malformed.includes('may use only letters'), `got "${malformed}"`);
  const still = await prisma.invoice.findUniqueOrThrow({ where: { id: inv3 }, select: { status: true, number: true } });
  ck('B7 and the note is left a draft, unnumbered', still.status === 'DRAFT' && still.number === null, `got ${JSON.stringify(still)}`);

  console.log('\nC. The count steps over a number typed ahead of it');
  ck('C1 typing the very number the count is up to', (await issue(inv3, `WF-DN-${YY}-0051`)).number === `WF-DN-${YY}-0051`);
  ck('C2 Settings then shows the one after', (await nextOf('INVOICE')) === `WF-DN-${YY}-0052`, `got ${await nextOf('INVOICE')}`);
  const inv4 = await draft();
  ck('C3 and the next note gets it, no collision', (await issue(inv4)).number === `WF-DN-${YY}-0052`);

  console.log('\nD. Receipts');
  const pay = (invoiceId: string, number?: string) =>
    payments.recordBulkPayment({ organizationId: orgId, tenantId: tenant.id, amount: '100.00', allocations: [{ invoiceId, amount: '100.00' }], number });
  const nextReceipt = await nextOf('RECEIPT');
  ck('D1 left blank, the receipt number Settings showed', (await pay(inv1)).number === nextReceipt, `expected ${nextReceipt}`);
  ck('D2 typed, as typed', (await pay(inv1, 'RE-OWN-1')).number === 'RE-OWN-1');
  ck('D3 typed twice, refused', (await refused(() => pay(inv1, 'RE-OWN-1'))) === 'Number RE-OWN-1 is already used');

  console.log('\nE. Deposit receipts');
  const dep = (number?: string) => deposits.create({ organizationId: orgId, tenantId: tenant.id, amount: '5000', number });
  const nextDeposit = await nextOf('DEPOSIT');
  ck('E1 left blank, the deposit number Settings showed', (await dep()).number === nextDeposit, `expected ${nextDeposit}`);
  ck('E2 typed, as typed', (await dep('DEP-OWN-1')).number === 'DEP-OWN-1');
  ck('E3 typed twice, refused', (await refused(() => dep('DEP-OWN-1'))) === 'Number DEP-OWN-1 is already used');

  console.log('\nF. Leases, through the same numbering as every other document');
  const leases = leasesRouter.createCaller(staffCtx(orgId));
  const mkLease = (reference?: string) =>
    leases.create({
      reference, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
      startDate: '2030-01-01', endDate: '2031-12-31', depositMonths: 0, unitIds: [property.units[0].id],
    });
  const refOf = async (id: string) => (await prisma.lease.findUniqueOrThrow({ where: { id }, select: { reference: true } })).reference;
  const nextLease = await nextOf('LEASE');
  ck('F1 left blank, the lease number Settings showed', (await refOf((await mkLease()).id)) === nextLease, `expected ${nextLease}`);
  ck('F2 typed, as typed', (await refOf((await mkLease('WF-L-001')).id)) === 'WF-L-001');
  ck('F3 typed twice, refused', (await refused(() => mkLease('WF-L-001'))) === 'Number WF-L-001 is already used');
  // The lease router used to number on its own and ignored the restart setting.
  await numbering.update({ docType: 'LEASE', prefix: 'L-', padding: 3, ...yearly, counts: [{ landlordId: null, nextValue: 7 }] });
  ck('F4 a yearly restart set in Settings now reaches leases too', (await refOf((await mkLease()).id)) === `L-${YY}-007`);

  console.log('\nG. Company code, year and month, as the ERP lays them out');
  // The ERP's own sample, DN-WF261001: each landlord company counts its own,
  // restarting every month. ZZ symbols keep clear of any real organisation's
  // numbers, which share the same unique columns.
  const [za, zb, zc] = await Promise.all(['ZA', 'ZB', 'ZC'].map((code) => prisma.landlord.create({ data: { organizationId: orgId, code, name: `ZZ Num ${code}` } })));
  const leaseOf = async (landlordId: string, reference: string) =>
    rentedLease(await prisma.property.create({ data: { organizationId: orgId, name: `ZZ Num ${reference}`, landlordId, units: { create: [{ name: 'ZZ G/F' }] } }, include: { units: true } }), reference);
  const leaseA = await leaseOf(za.id, 'ZZ-NUM-A');
  const leaseB = await leaseOf(zb.id, 'ZZ-NUM-B');
  const erp = { prefix: 'ZZDN', text1: '-', text2: '', parts: [...ERP_PARTS], padding: 2, resetPeriod: 'MONTHLY' as const };
  await numbering.update({ docType: 'INVOICE', ...erp });
  ck('G1 Settings shows the first company’s next number', (await nextOf('INVOICE')) === `ZZDN-ZA${YYMM}01`, `got ${await nextOf('INVOICE')}`);
  const invA1 = await issue(await draftOf(leaseA.id, '2020-01'));
  ck('G2 a debit note carries its landlord’s code and the month it was issued', invA1.number === `ZZDN-ZA${YYMM}01`, `got ${invA1.number}`);
  const invB1 = await issue(await draftOf(leaseB.id, '2020-01'));
  ck('G3 another company’s first note of the month is its own 01', invB1.number === `ZZDN-ZB${YYMM}01`, `got ${invB1.number}`);
  const invA2 = await issue(await draftOf(leaseA.id, '2020-02'));
  ck('G4 the first company carries on from where it was', invA2.number === `ZZDN-ZA${YYMM}02`, `got ${invA2.number}`);
  const unowned = await draft();
  const noLandlord = await refused(() => issue(unowned));
  ck('G5 a note for a property with no landlord is refused, saying what to set', noLandlord === "ZZ Num Property has no landlord, so the number has no company code to carry; set the property's landlord first", `got "${noLandlord}"`);
  ck('G6 but takes a number typed for it', (await issue(unowned, 'ZZDN-OWN-9')).number === 'ZZDN-OWN-9');
  // Picking up mid-month from where the ERP had got to, for one company.
  await numbering.update({ docType: 'INVOICE', ...erp, counts: [{ landlordId: zb.id, nextValue: 6 }] });
  const invB2 = await issue(await draftOf(leaseB.id, '2020-02'));
  ck('G7 one company’s count can be set on its own', invB2.number === `ZZDN-ZB${YYMM}06`, `got ${invB2.number}`);
  ck('G8 leaving the others where they were', (await nextOf('INVOICE')) === `ZZDN-ZA${YYMM}03`, `got ${await nextOf('INVOICE')}`);
  const counts = (await numbering.list()).sequences.find((r) => r.docType === 'INVOICE')?.counts ?? {};
  const thisMonth = hkDay(new Date()).slice(0, 6);
  ck('G9 Settings has this month’s count for each company', counts[`${thisMonth}|${za.id}`] === 3 && counts[`${thisMonth}|${zb.id}`] === 7, JSON.stringify(counts));

  await numbering.update({ docType: 'RECEIPT', prefix: 'ZZRE', text1: '', text2: '', parts: ['SYMBOL', 'COMPANY', 'YEAR', 'MONTH', 'SERIAL'], padding: 3, resetPeriod: 'MONTHLY' });
  const lastMonth = new Date(Date.UTC(Number(thisMonth.slice(0, 4)), Number(thisMonth.slice(4)) - 2, 15));
  const payNotes = (invoiceIds: string[], number?: string, receivedDate?: Date) =>
    payments.recordBulkPayment({
      organizationId: orgId, tenantId: tenant.id, amount: (100 * invoiceIds.length).toFixed(2),
      allocations: invoiceIds.map((invoiceId) => ({ invoiceId, amount: '100.00' })), number, receivedDate,
    });
  const late = await payNotes([invA1.id], undefined, lastMonth);
  ck('G10 a receipt entered today for money received last month takes last month’s number', late.number === `ZZREZA${hkDay(lastMonth).slice(2, 6)}001`, `got ${late.number}`);
  const prompt = await payNotes([invA1.id]);
  ck('G11 and this month’s count starts on its own', prompt.number === `ZZREZA${YYMM}001`, `got ${prompt.number}`);
  const mixed = await refused(() => payNotes([invA1.id, invB1.id]));
  ck('G12 one payment for two companies’ notes is refused', mixed === 'These debit notes belong to different landlord companies; record a separate payment for each', `got "${mixed}"`);
  ck('G13 unless its number is typed — then no company code is needed', (await payNotes([invA1.id, invB1.id], 'ZZRE-OWN-1')).number === 'ZZRE-OWN-1');

  await numbering.update({ docType: 'DEPOSIT', prefix: 'ZZDEP', text1: '', text2: '', parts: ['SYMBOL', 'COMPANY', 'SERIAL'], padding: 4, resetPeriod: 'NEVER' });
  const noLease = await refused(() => dep());
  ck('G14 a deposit taken for no lease is refused a company number', noLease === 'This document is not for a lease, so its number has no company code to carry; link it to a lease, or type its number', `got "${noLease}"`);
  const depB = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: leaseB.id, amount: '5000' });
  ck('G15 one for a lease carries its landlord’s code, the count never restarting', depB.number === 'ZZDEPZB0001', `got ${depB.number}`);

  await numbering.update({ docType: 'LEASE', prefix: 'ZZL', text1: '/', text2: '', parts: ['COMPANY', 'TEXT1', 'SYMBOL', 'YEAR', 'SERIAL'], padding: 3, resetPeriod: 'YEARLY' });
  const companyFirst = await leases.create({
    tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2031-12-31', depositMonths: 0, unitIds: [leaseB.units[0].unitId],
  });
  ck('G16 the parts go in the office’s order — here the company first', (await refOf(companyFirst.id)) === `ZB/ZZL${YY}001`, `got ${await refOf(companyFirst.id)}`);

  // The day, as in the ERP, is only shown: a monthly count carries on through it.
  await numbering.update({ docType: 'RECEIPT', prefix: 'ZZRE', text1: '', text2: '', parts: ['SYMBOL', 'COMPANY', 'YEAR', 'MONTH', 'DAY', 'SERIAL'], padding: 3, resetPeriod: 'MONTHLY' });
  const dated = await payNotes([invA1.id], undefined, lastMonth);
  ck('G17 the day received goes in the number, the month’s count carrying on', dated.number === `ZZREZA${hkDay(lastMonth).slice(2)}002`, `got ${dated.number}`);

  console.log('\nH. Many at once');
  // Four notes of a company with no count yet this month, issued together: the
  // first starts the count while the rest wait on it, so none share a number.
  const zcDrafts: string[] = [];
  for (const n of [1, 2, 3, 4]) zcDrafts.push(await draftOf((await leaseOf(zc.id, `ZZ-NUM-C${n}`)).id, '2020-01'));
  const together = await Promise.allSettled(zcDrafts.map((id) => issue(id)));
  const failed = together.flatMap((r) => (r.status === 'rejected' ? [String(r.reason)] : []));
  const got = together.flatMap((r) => (r.status === 'fulfilled' ? [r.value.number] : [])).sort();
  ck('H1 four notes issued at once take 01 to 04, none twice', failed.length === 0 && JSON.stringify(got) === JSON.stringify([1, 2, 3, 4].map((n) => `ZZDN-ZC${YYMM}0${n}`)), `got ${JSON.stringify(got)} ${failed.join(' | ')}`);
}

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  const invIds = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
  const depIds = (await prisma.deposit.findMany({ where, select: { id: true } })).map((d) => d.id);
  const rcpIds = (await prisma.receipt.findMany({ where, select: { id: true } })).map((r) => r.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 } } });
  await prisma.receiptAllocationItem.deleteMany({ where: { allocation: { receiptId: { in: rcpIds } } } });
  await prisma.receiptAllocation.deleteMany({ where: { receiptId: { in: rcpIds } } });
  await prisma.receipt.deleteMany({ where: { id: { in: rcpIds } } });
  await prisma.deposit.deleteMany({ where: { id: { in: depIds } } });
  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.landlord.deleteMany({ where });
  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); });
