/**
 * Shared smoke helper: issue a debit note, walking its approval workflow first
 * when the organization has one that applies.
 *
 * Smokes that run under the demo org exercise billing, the ledger or deposits —
 * not approval routing — so they must not break just because the org gates its
 * debit notes. This signs each step as a throwaway user granted that step's
 * role, then issues. Call purgeSmokeApprover() from the smoke's cleanup.
 */
import type { ApprovalService } from '../src/approvals/approval.service';
import type { BillingService } from '../src/billing/billing.service';
import type { PrismaService } from '../src/prisma/prisma.service';

const APPROVER_EMAIL = 'zz-smoke-approver@rms.local';

/** Documents this helper opened a round on, so the cleanup can close them out.
 * A smoke's own purge deletes its invoices but knows nothing about approvals. */
const touched = new Set<string>();

export interface SmokeDeps {
  prisma: PrismaService;
  billing: BillingService;
  approvals: ApprovalService;
}

export async function issueInvoice(deps: SmokeDeps, organizationId: string, invoiceId: string, issuedByUserId?: string) {
  const { billing } = deps;
  try {
    return await billing.issue({ organizationId, invoiceId, issuedByUserId });
  } catch (err) {
    // Anything other than "this needs approval first" is a real failure.
    if (!(err instanceof Error) || !err.message.includes('needs approval')) throw err;
  }
  await approveInvoice(deps, organizationId, invoiceId);
  return billing.issue({ organizationId, invoiceId, issuedByUserId });
}

/** Walks a note's approval to the end and stops there, leaving it APPROVED. What
 * issueInvoice does before issuing — separate so a smoke can exercise an
 * approved-but-unissued note, which is the state a deferred send sits in. */
export async function approveInvoice(deps: SmokeDeps, organizationId: string, invoiceId: string): Promise<void> {
  const { prisma, billing, approvals } = deps;
  await billing.submitForApproval({ organizationId, invoiceId });
  touched.add(invoiceId);
  const approver = await prisma.user.upsert({
    where: { email: APPROVER_EMAIL },
    update: {},
    create: { email: APPROVER_EMAIL, name: 'Smoke approver', passwordHash: 'x' },
  });

  // Sign each step in turn. The bound is a runaway guard, not a real limit.
  for (let step = 0; step < 20; step++) {
    const inst = await prisma.approvalInstance.findFirst({
      where: { documentType: 'INVOICE', documentId: invoiceId, isComplete: false, cancelledAt: null },
      include: { workflow: { include: { steps: true } } },
    });
    if (!inst) break;
    const current = inst.workflow.steps.find((s) => s.stepOrder === inst.currentStep);
    if (!current) throw new Error(`smoke: no approval step at position ${inst.currentStep}`);
    if (current.actorType === 'ROLE' && current.actorRoleId) {
      await prisma.userRole.upsert({
        where: { userId_roleId: { userId: approver.id, roleId: current.actorRoleId } },
        update: {},
        create: { userId: approver.id, roleId: current.actorRoleId },
      });
    }
    const userId = current.actorType === 'USER' ? current.actorUserId ?? approver.id : approver.id;
    await approvals.act({ organizationId, userId, instanceId: inst.id, action: 'APPROVE' });
  }
}

/** Undo everything issueInvoice may have left behind: the rounds it opened (the
 * smoke's own purge deletes the invoices but not their approvals) and the
 * throwaway approver with its granted roles. */
export async function purgeSmokeApprover(prisma: PrismaService): Promise<void> {
  const ids = [...touched];
  if (ids.length) {
    await prisma.approvalAction.deleteMany({ where: { instance: { documentType: 'INVOICE', documentId: { in: ids } } } });
    await prisma.approvalInstance.deleteMany({ where: { documentType: 'INVOICE', documentId: { in: ids } } });
    touched.clear();
  }
  const user = await prisma.user.findUnique({ where: { email: APPROVER_EMAIL }, select: { id: true } });
  if (!user) return;
  await prisma.approvalAction.deleteMany({ where: { actedById: user.id } });
  await prisma.userRole.deleteMany({ where: { userId: user.id } });
  await prisma.user.delete({ where: { id: user.id } });
}
