/**
 * Smoke for the debit-note approval stage: DRAFT → PENDING_APPROVAL → APPROVED
 * → ISSUED, editing restarts the round, rejection returns to DRAFT, and a note
 * that drops below every threshold leaves approval altogether.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/invoice-approval-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Decimal } from '@rms/domain';
import { ApprovalService } from '../src/approvals/approval.service';
import { BillingService } from '../src/billing/billing.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { NumberService } from '../src/common/number.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { appRouter } from '../src/trpc/app-router';

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), approvals);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
const throws = async (n: string, fn: () => Promise<unknown>, needle: string) => {
  try { await fn(); ck(n, false, 'did not throw'); }
  catch (e) { const m = e instanceof Error ? e.message : String(e); ck(n, m.includes(needle), `got "${m}"`); }
};

// The smoke runs in its own organization: approval requirements are org-scoped,
// so a workflow configured in the real org must not decide these assertions.
const PFX = 'ZZ-APR';
const ORG_CODE = `${PFX}-ORG`;

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  const orgId = org?.id ?? '';
  const invoices = await prisma.invoice.findMany({ where: { lease: { reference: { startsWith: PFX } } }, select: { id: true } });
  const invIds = invoices.map((i) => i.id);
  if (invIds.length) {
    await prisma.approvalAction.deleteMany({ where: { instance: { documentId: { in: invIds } } } });
    await prisma.approvalInstance.deleteMany({ where: { documentId: { in: invIds } } });
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
  }
  await prisma.lease.deleteMany({ where: { reference: { startsWith: PFX } } });
  const props = await prisma.property.findMany({ where: { organizationId: orgId, name: `${PFX} Property` }, select: { id: true } });
  if (props.length) {
    await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
    await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
  }
  await prisma.tenant.deleteMany({ where: { organizationId: orgId, name: `${PFX} Tenant` } });
  const wfs = await prisma.approvalWorkflow.findMany({ where: { organizationId: orgId, code: { startsWith: PFX } }, select: { id: true } });
  if (wfs.length) {
    await prisma.approvalStep.deleteMany({ where: { workflowId: { in: wfs.map((w) => w.id) } } });
    await prisma.approvalWorkflow.deleteMany({ where: { id: { in: wfs.map((w) => w.id) } } });
  }
  const users = await prisma.user.findMany({ where: { email: { startsWith: `${PFX}-` } }, select: { id: true } });
  if (users.length) {
    await prisma.userRole.deleteMany({ where: { userId: { in: users.map((u) => u.id) } } });
    await prisma.user.deleteMany({ where: { id: { in: users.map((u) => u.id) } } });
  }
  await prisma.chargeType.deleteMany({ where: { organizationId: orgId, code: { startsWith: PFX } } });
  await prisma.role.deleteMany({ where: { code: { startsWith: PFX } } });
  if (org) await prisma.organization.delete({ where: { id: org.id } });
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Approval smoke org' } })).id;

  // ── fixtures ────────────────────────────────────────────────
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant` } });
  const prop = await prisma.property.create({ data: { organizationId: orgId, name: `${PFX} Property`, units: { create: { name: `${PFX} U1` } } } });
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${PFX}-L1`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2026-01-01'), endDate: new Date('2026-12-31'), depositMonths: 0,
    },
  });
  const r1 = await prisma.role.create({ data: { code: `${PFX}-R1`, name: 'Smoke supervisor' } });
  const r2 = await prisma.role.create({ data: { code: `${PFX}-R2`, name: 'Smoke director' } });
  const user = await prisma.user.create({
    data: { email: `${PFX}-approver@example.com`, name: 'Smoke Approver', passwordHash: 'x', roles: { create: [{ roleId: r1.id }, { roleId: r2.id }] } },
  });
  const wf = await prisma.approvalWorkflow.create({
    data: {
      organizationId: orgId, documentType: 'INVOICE', code: `${PFX}-WF`, name: 'Smoke approval', minAmount: '5000', isActive: true,
      steps: { create: [
        { stepOrder: 1, name: 'Supervisor', actorType: 'ROLE', actorRoleId: r1.id },
        { stepOrder: 2, name: 'Director', actorType: 'ROLE', actorRoleId: r2.id },
      ] },
    },
  });

  const mkInvoice = async (period: string, rent: string, interest: string) =>
    prisma.invoice.create({
      data: {
        organizationId: orgId, leaseId: lease.id, status: 'DRAFT', currency: 'HKD', billingPeriod: period, dueDate: new Date('2026-02-01'),
        lines: { create: [
          { kind: 'CHARGE', description: 'Rent', amount: rent, sortOrder: 10 },
          { kind: 'INTEREST', description: 'Late interest', amount: interest, sortOrder: 20 },
        ] },
      },
    });

  const statusOf = async (id: string) => (await prisma.invoice.findUniqueOrThrow({ where: { id }, select: { status: true } })).status;
  const state = (id: string) => approvals.documentState(orgId, 'INVOICE', id, user.id);

  // ── A: full happy path, then edit → restart, then reject → DRAFT ──
  console.log('\nA. approval lifecycle');
  const a = await mkInvoice('2026-01', '10000', '500');

  await throws('A0 issuing before submitting is refused', () => billing.issue({ organizationId: orgId, invoiceId: a.id }), 'needs approval');

  const sub = await billing.submitForApproval({ organizationId: orgId, invoiceId: a.id });
  ck('A1 submit moves DRAFT → PENDING_APPROVAL', (await statusOf(a.id)) === 'PENDING_APPROVAL', await statusOf(a.id));
  ck('A2 submit reports the workflow + step count', sub.workflowName === wf.name && sub.totalSteps === 2, JSON.stringify(sub));

  await throws('A3 issuing while in approval is refused', () => billing.issue({ organizationId: orgId, invoiceId: a.id }), 'awaiting approval');

  const s1 = await state(a.id);
  ck('A4 round 1 is open at step 1/2', s1.current?.round === 1 && s1.current?.currentStep === 1 && s1.current?.totalSteps === 2, JSON.stringify(s1.current));
  ck('A5 the assigned approver can act', s1.canAct === true);

  await approvals.act({ organizationId: orgId, userId: user.id, instanceId: s1.current!.instanceId, action: 'APPROVE' });
  ck('A6 step 1 signed → still PENDING_APPROVAL', (await statusOf(a.id)) === 'PENDING_APPROVAL', await statusOf(a.id));
  const s2 = await state(a.id);
  ck('A7 advanced to step 2', s2.current?.currentStep === 2, JSON.stringify(s2.current));

  await approvals.act({ organizationId: orgId, userId: user.id, instanceId: s2.current!.instanceId, action: 'APPROVE' });
  ck('A8 last step signed → APPROVED', (await statusOf(a.id)) === 'APPROVED', await statusOf(a.id));

  // Once signed off, the figures are settled — see block E.
  await throws(
    'A9 an approved note can no longer be edited',
    () => billing.waiveInterest({ organizationId: orgId, invoiceId: a.id }),
    'approved one must be voided',
  );

  // The restart-on-edit rule still applies while a note is IN approval, which
  // is where a correction actually belongs. A fresh note, signed once.
  const a2 = await mkInvoice('2026-08', '10000', '500');
  await billing.submitForApproval({ organizationId: orgId, invoiceId: a2.id });
  const r1a = await state(a2.id);
  await approvals.act({ organizationId: orgId, userId: user.id, instanceId: r1a.current!.instanceId, action: 'APPROVE' });
  ck('A10 one signature collected, still in approval', (await statusOf(a2.id)) === 'PENDING_APPROVAL', await statusOf(a2.id));

  await billing.waiveInterest({ organizationId: orgId, invoiceId: a2.id });
  const s3 = await state(a2.id);
  ck('A11 an edit reopens at round 2, step 1', s3.current?.round === 2 && s3.current?.currentStep === 1, JSON.stringify(s3.current));
  ck('A12 round 1 is kept as superseded', s3.rounds.find((r) => r.round === 1)?.status === 'CANCELLED', JSON.stringify(s3.rounds.map((r) => r.status)));
  ck('A13 and keeps the signature it had collected', (s3.rounds.find((r) => r.round === 1)?.actions.length ?? 0) === 1);

  await approvals.act({ organizationId: orgId, userId: user.id, instanceId: s3.current!.instanceId, action: 'REJECT', note: 'wrong figures' });
  ck('A14 rejection returns the note to DRAFT', (await statusOf(a2.id)) === 'DRAFT', await statusOf(a2.id));
  const s4 = await state(a2.id);
  ck('A15 round 2 is recorded as REJECTED', s4.rounds.find((r) => r.round === 2)?.status === 'REJECTED');
  ck('A16 no round is open after rejection', s4.current === null);

  await billing.submitForApproval({ organizationId: orgId, invoiceId: a2.id });
  const s5 = await state(a2.id);
  ck('A17 a corrected note can be re-submitted as round 3', s5.current?.round === 3, JSON.stringify(s5.current));
  ck('A18 all three rounds are on file', s5.rounds.length === 3, `${s5.rounds.length}`);

  // ── B: an edit that drops below every threshold leaves approval ──
  console.log('\nB. falling below the threshold');
  const b = await mkInvoice('2026-02', '4000', '2000');
  await billing.submitForApproval({ organizationId: orgId, invoiceId: b.id });
  ck('B1 6000 ≥ 5000 → PENDING_APPROVAL', (await statusOf(b.id)) === 'PENDING_APPROVAL', await statusOf(b.id));
  await billing.waiveInterest({ organizationId: orgId, invoiceId: b.id });
  ck('B2 4000 < 5000 → back to DRAFT, no approval needed', (await statusOf(b.id)) === 'DRAFT', await statusOf(b.id));
  const sb = await state(b.id);
  ck('B3 the abandoned round is superseded', sb.current === null && sb.rounds.every((r) => r.status === 'CANCELLED'), JSON.stringify(sb.rounds.map((r) => r.status)));

  // ── C: no workflow applies → nothing to approve ──
  console.log('\nC. under every threshold from the start');
  const c = await mkInvoice('2026-03', '1000', '0');
  const sc = await approvals.documentState(orgId, 'INVOICE', c.id, user.id, new Decimal('1000'));
  ck('C1 no approval is required', sc.required === false);
  await throws('C2 submitting is refused when no workflow applies', () => billing.submitForApproval({ organizationId: orgId, invoiceId: c.id }), 'No approval workflow');
  ck('C3 it stays a DRAFT', (await statusOf(c.id)) === 'DRAFT', await statusOf(c.id));

  // ── D: a superseded round can no longer be acted on ──
  console.log('\nD. acting on a superseded round');
  const d = await mkInvoice('2026-04', '9000', '1000');
  await billing.submitForApproval({ organizationId: orgId, invoiceId: d.id });
  const sd = await state(d.id);
  await billing.waiveInterest({ organizationId: orgId, invoiceId: d.id });
  await throws(
    'D1 the stale instance id is rejected',
    () => approvals.act({ organizationId: orgId, userId: user.id, instanceId: sd.current!.instanceId, action: 'APPROVE' }),
    'superseded',
  );

  // ── E. an approved note is closed to edits ──
  // Signatures were given against those figures. Changing the lines afterwards
  // would leave the signatures describing a document that no longer exists, so
  // the only correction is to void it and raise it again.
  console.log('');
  console.log('E. Approved means settled — the lines are closed');
  // Same fixture shape as the rest of this smoke — over the workflow's 5000
  // threshold so approval actually applies.
  // This smoke runs in its own empty organisation, so it brings its own.
  const adjustCt = await prisma.chargeType.create({
    data: { organizationId: orgId, code: `${PFX}ADJ`, nameEn: 'Smoke adjustment', category: 'ADJUSTMENT', isActive: true },
  });
  const e = await mkInvoice('2026-09', '9000', '0');
  await billing.submitForApproval({ organizationId: orgId, invoiceId: e.id });
  const se1 = await state(e.id);
  await approvals.act({ organizationId: orgId, userId: user.id, instanceId: se1.current!.instanceId, action: 'APPROVE' });
  const se2 = await state(e.id);
  if (se2.current) await approvals.act({ organizationId: orgId, userId: user.id, instanceId: se2.current.instanceId, action: 'APPROVE' });
  ck('E1 it reaches APPROVED', (await statusOf(e.id)) === 'APPROVED', await statusOf(e.id));

  const someLine = (await prisma.invoiceLine.findFirstOrThrow({ where: { invoiceId: e.id, kind: 'CHARGE' }, select: { id: true } })).id;
  const linesBefore = await prisma.invoiceLine.count({ where: { invoiceId: e.id } });
  await throws('E2 a line cannot be removed', () => billing.removeLine({ organizationId: orgId, lineId: someLine }), 'approved one must be voided');
  await throws(
    'E3 an adjustment cannot be added',
    () => billing.addAdjustment({ organizationId: orgId, invoiceId: e.id, chargeTypeId: adjustCt.id, description: 'ZZ nope', amount: '1', credit: false }),
    'approved one must be voided',
  );
  await throws('E4 interest cannot be waived', () => billing.waiveInterest({ organizationId: orgId, invoiceId: e.id }), 'approved one must be voided');
  await throws('E5 it cannot be rebuilt', () => billing.regenerateDraft({ organizationId: orgId, invoiceId: e.id }), 'approved one must be voided');
  ck('E6 and nothing changed', (await prisma.invoiceLine.count({ where: { invoiceId: e.id } })) === linesBefore);

  // The escape hatch has to stay open, or an approved note with a mistake is
  // stuck forever: void is now the ONLY way to correct one.
  await billing.voidInvoice({ organizationId: orgId, invoiceId: e.id });
  ck('E7 but it can still be voided — the only way to correct it', (await statusOf(e.id)) === 'VOID', await statusOf(e.id));

  // ── F. rejecting requires a reason ──
  console.log('');
  console.log('F. A refusal has to say why');
  const f = await mkInvoice('2026-10', '9000', '0');
  await billing.submitForApproval({ organizationId: orgId, invoiceId: f.id });
  const sf = await state(f.id);
  // The requirement is on the router's input, which is where every caller goes
  // through — asserting on the service would prove nothing about the screens.
  const caller = appRouter.createCaller({
    prisma,
    user: { id: user.id, email: 'zz@rms.local', name: 'ZZ', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions: ['invoice.read'] },
    organizationId: orgId,
    approvals,
  } as unknown as Parameters<typeof appRouter.createCaller>[0]);
  let blank = '';
  try {
    await caller.approvals.act({ instanceId: sf.current!.instanceId, action: 'REJECT' });
  } catch (err) {
    blank = err instanceof Error ? err.message : String(err);
  }
  ck('F1 rejecting with no reason is refused', blank !== '', 'a bare "rejected" tells the person who raised it nothing');
  ck('F2 and the round is still open', (await state(f.id)).current !== null);
  let whitespace = '';
  try {
    await caller.approvals.act({ instanceId: sf.current!.instanceId, action: 'REJECT', note: '   ' });
  } catch (err) {
    whitespace = err instanceof Error ? err.message : String(err);
  }
  ck('F3 whitespace does not count as a reason', whitespace !== '');
  await caller.approvals.act({ instanceId: sf.current!.instanceId, action: 'REJECT', note: 'ZZ figures are wrong' });
  const rejected = await state(f.id);
  ck('F4 with a reason it goes through', rejected.current === null);
  ck('F5 and the reason is kept', rejected.rounds.some((r) => r.actions.some((a) => a.note === 'ZZ figures are wrong')));
  // Approving needs no words — the requirement is on refusal only.
  ck('F6 the note returns to DRAFT, so it can be corrected', (await statusOf(f.id)) === 'DRAFT', await statusOf(f.id));
}


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