import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, type ApprovalStep } from '@prisma/client';
import { Decimal } from '@rms/domain';
import { PrismaService } from '../prisma/prisma.service';
import { CURRENCY_SYMBOLS } from '@rms/domain';

export type ApprovalStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'CANCELLED';

export interface GateResult {
  required: boolean;
  status: ApprovalStatus;
  instanceId?: string;
  workflowName?: string;
}

export interface SubmitResult {
  required: boolean;
  status?: ApprovalStatus;
  instanceId?: string;
  workflowName?: string;
  totalSteps?: number;
}

/** A round still awaiting action: neither settled nor invalidated by an edit. */
const OPEN = { isComplete: false, cancelledAt: null } as const;

@Injectable()
export class ApprovalService {
  constructor(private readonly prisma: PrismaService) {}

  /** Runs against the caller's transaction when given one, else the pool. */
  private db(tx?: Prisma.TransactionClient): Prisma.TransactionClient {
    return tx ?? (this.prisma as unknown as Prisma.TransactionClient);
  }

  /** The active workflow that applies to a document of this type + amount, if
   * any. Most-specific threshold (highest minAmount ≤ amount) wins. */
  async requirementFor(organizationId: string, documentType: string, amount: Decimal, tx?: Prisma.TransactionClient) {
    const workflows = await this.db(tx).approvalWorkflow.findMany({
      where: { organizationId, documentType, isActive: true },
      include: { steps: { orderBy: { stepOrder: 'asc' } } },
    });
    const applicable = workflows.filter(
      (w) => w.steps.length > 0 && (w.minAmount == null || new Decimal(w.minAmount.toString()).lte(amount)),
    );
    if (applicable.length === 0) return null;
    applicable.sort((a, b) => Number(b.minAmount ?? -1) - Number(a.minAmount ?? -1));
    return applicable[0];
  }

  /** Called by an operation that gates at the moment of action (a deposit refund
   * checks this when it is paid). If a workflow applies it ensures a round
   * exists and reports its status; callers block on PENDING / REJECTED.
   * Idempotent — the latest live round is reused, never duplicated. */
  async gate(organizationId: string, documentType: string, documentId: string, amount: Decimal): Promise<GateResult> {
    const wf = await this.requirementFor(organizationId, documentType, amount);
    if (!wf) return { required: false, status: 'APPROVED' };

    const existing = await this.latestLive(documentType, documentId);
    if (existing) {
      return { required: true, status: deriveStatus(existing), instanceId: existing.id, workflowName: existing.workflow.name };
    }
    const inst = await this.openRound(wf.id, documentType, documentId);
    return { required: true, status: deriveStatus(inst), instanceId: inst.id, workflowName: inst.workflow.name };
  }

  /** Explicitly starts an approval round (the "send for approval" action). Unlike
   * gate(), a settled round does not block: a rejected document that has since
   * been corrected opens round N+1, keeping the earlier round as history. */
  async submit(
    organizationId: string,
    documentType: string,
    documentId: string,
    amount: Decimal,
    tx?: Prisma.TransactionClient,
  ): Promise<SubmitResult> {
    const wf = await this.requirementFor(organizationId, documentType, amount, tx);
    if (!wf) return { required: false };

    const open = await this.db(tx).approvalInstance.findFirst({
      where: { documentType, documentId, ...OPEN },
      orderBy: { round: 'desc' },
      include: { actions: true, workflow: { include: { steps: true } } },
    });
    if (open) {
      return {
        required: true,
        status: deriveStatus(open),
        instanceId: open.id,
        workflowName: open.workflow.name,
        totalSteps: open.workflow.steps.length,
      };
    }
    const inst = await this.openRound(wf.id, documentType, documentId, tx);
    return {
      required: true,
      status: deriveStatus(inst),
      instanceId: inst.id,
      workflowName: inst.workflow.name,
      totalSteps: wf.steps.length,
    };
  }

  /** Invalidates the document's latest round — used when the document itself
   * changed, so signatures collected against the old figures cannot stand. */
  async supersede(documentType: string, documentId: string, tx?: Prisma.TransactionClient): Promise<void> {
    const latest = await this.db(tx).approvalInstance.findFirst({
      where: { documentType, documentId, cancelledAt: null },
      orderBy: { round: 'desc' },
      select: { id: true },
    });
    if (!latest) return;
    await this.db(tx).approvalInstance.update({ where: { id: latest.id }, data: { cancelledAt: new Date() } });
  }

  /** Everything the UI needs to render a document's approval box: whether one is
   * required at the current amount, the live round, whether the signed-in user
   * can act on it, and every round's signature trail. */
  async documentState(
    organizationId: string,
    documentType: string,
    documentId: string,
    userId: string,
    amount?: Decimal,
  ) {
    const instances = await this.prisma.approvalInstance.findMany({
      where: { documentType, documentId, workflow: { organizationId } },
      orderBy: { round: 'asc' },
      include: {
        workflow: { include: { steps: { orderBy: { stepOrder: 'asc' } } } },
        actions: { orderBy: { actedAt: 'asc' } },
      },
    });

    const actorIds = [...new Set(instances.flatMap((i) => i.actions.map((a) => a.actedById)))];
    const actors = actorIds.length
      ? await this.prisma.user.findMany({ where: { id: { in: actorIds } }, select: { id: true, name: true } })
      : [];
    const actorName = new Map(actors.map((u) => [u.id, u.name]));

    const open = instances.find((i) => !i.isComplete && i.cancelledAt === null) ?? null;
    const openStep = open ? open.workflow.steps.find((s) => s.stepOrder === open.currentStep) ?? null : null;
    const required = amount === undefined ? open !== null : Boolean(await this.requirementFor(organizationId, documentType, amount));

    return {
      required,
      canAct: open && openStep ? await this.isActor(this.db(), openStep, userId) : false,
      current: open
        ? {
            instanceId: open.id,
            round: open.round,
            workflowName: open.workflow.name,
            currentStep: open.currentStep,
            totalSteps: open.workflow.steps.length,
            stepName: openStep?.name ?? null,
          }
        : null,
      rounds: instances.map((i) => ({
        round: i.round,
        workflowName: i.workflow.name,
        status: deriveStatus(i),
        createdAt: i.createdAt,
        actions: i.actions.map((a) => ({
          stepOrder: a.stepOrder,
          stepName: i.workflow.steps.find((s) => s.stepOrder === a.stepOrder)?.name ?? null,
          action: a.action,
          actorName: actorName.get(a.actedById) ?? null,
          note: a.note,
          actedAt: a.actedAt,
        })),
      })),
    };
  }

  /** Act on the CURRENT step. Only the step's assigned actor (role membership or
   * the named user) may act. APPROVE advances / completes; REJECT ends it. */
  async act(input: {
    organizationId: string;
    userId: string;
    instanceId: string;
    action: 'APPROVE' | 'REJECT';
    note?: string | null;
  }): Promise<{ ok: true; status: ApprovalStatus }> {
    return this.prisma.$transaction(async (tx) => {
      const inst = await tx.approvalInstance.findFirst({ where: { id: input.instanceId } });
      if (!inst) throw new NotFoundException('Approval not found');
      if (inst.cancelledAt) throw new BadRequestException('This approval round was superseded by a change to the document');
      if (inst.isComplete) throw new BadRequestException('This approval is already closed');

      const wf = await tx.approvalWorkflow.findFirst({
        where: { id: inst.workflowId, organizationId: input.organizationId },
        include: { steps: { orderBy: { stepOrder: 'asc' } } },
      });
      if (!wf) throw new NotFoundException('Workflow not found');
      const step = wf.steps.find((s) => s.stepOrder === inst.currentStep);
      if (!step) throw new BadRequestException('No step at the current position');

      if (!(await this.isActor(tx, step, input.userId))) {
        throw new ForbiddenException('You are not the approver for this step');
      }

      const maxStep = Math.max(...wf.steps.map((s) => s.stepOrder));
      let status: ApprovalStatus;
      let advance: { isComplete?: boolean; currentStep?: number };
      if (input.action === 'REJECT') {
        advance = { isComplete: true };
        status = 'REJECTED';
      } else if (inst.currentStep >= maxStep) {
        advance = { isComplete: true };
        status = 'APPROVED';
      } else {
        advance = { currentStep: inst.currentStep + 1 };
        status = 'PENDING';
      }

      // Compare-and-swap on the current step: only the first concurrent actor on
      // this step wins; a second (same-role) approver acting at once matches 0
      // rows and is rejected, so no duplicate action / double-advance. The
      // cancelledAt guard also loses the race against a concurrent edit.
      const claim = await tx.approvalInstance.updateMany({
        where: { id: inst.id, currentStep: inst.currentStep, ...OPEN },
        data: advance,
      });
      if (claim.count !== 1) throw new BadRequestException('This step was already actioned');

      await tx.approvalAction.create({
        data: { instanceId: inst.id, stepOrder: inst.currentStep, action: input.action, actedById: input.userId, note: input.note ?? null },
      });
      await this.syncDocumentStatus(tx, inst.documentType, inst.documentId, status);
      return { ok: true, status };
    });
  }

  /** The signed-in user's action inbox: open rounds whose current step is
   * assigned to them (by role membership or by name). */
  async pending(organizationId: string, userId: string) {
    const open = await this.prisma.approvalInstance.findMany({
      where: { ...OPEN, workflow: { organizationId } },
      orderBy: { createdAt: 'asc' },
      include: { workflow: { include: { steps: true } } },
    });
    if (open.length === 0) return [];
    const roleIds = (await this.prisma.userRole.findMany({ where: { userId }, select: { roleId: true } })).map((r) => r.roleId);

    const mine = open
      .map((inst) => {
        const step = inst.workflow.steps.find((s) => s.stepOrder === inst.currentStep);
        if (!step) return null;
        const isMine = step.actorType === 'USER' ? step.actorUserId === userId : Boolean(step.actorRoleId && roleIds.includes(step.actorRoleId));
        if (!isMine) return null;
        return {
          instanceId: inst.id,
          documentType: inst.documentType,
          documentId: inst.documentId,
          workflowName: inst.workflow.name,
          stepName: step.name,
          currentStep: inst.currentStep,
          totalSteps: inst.workflow.steps.length,
          createdAt: inst.createdAt,
          documentLabel: null as string | null,
          // Set for DEPOSIT_REFUND below, so the inbox can open the deposit the
          // payout belongs to — the approver was otherwise signing blind.
          depositId: null as string | null,
        };
      })
      .filter((x): x is NonNullable<typeof x> => x !== null);

    // Enrich INVOICE documents with a human label (number + amount).
    const invIds = mine.filter((m) => m.documentType === 'INVOICE').map((m) => m.documentId);
    if (invIds.length > 0) {
      const invs = await this.prisma.invoice.findMany({
        where: { id: { in: invIds } },
        include: { lines: { select: { amount: true } }, lease: { select: { reference: true } } },
      });
      const label = new Map(
        invs.map((i) => {
          const total = i.lines.reduce((s, l) => s + Number(l.amount.toString()), 0);
          return [i.id, `${i.number ?? i.billingPeriod} · ${i.lease.reference} · HK$${total.toLocaleString('en-US', { minimumFractionDigits: 2 })}`];
        }),
      );
      for (const m of mine) if (m.documentType === 'INVOICE') m.documentLabel = label.get(m.documentId) ?? null;
    }

    // Enrich DEPOSIT_REFUND documents (documentId = settlement id) with a label.
    const refundIds = mine.filter((m) => m.documentType === 'DEPOSIT_REFUND').map((m) => m.documentId);
    if (refundIds.length > 0) {
      const settlements = await this.prisma.depositSettlement.findMany({
        where: { id: { in: refundIds } },
        include: { deposit: { include: { tenant: { select: { name: true } } } } },
      });
      const label = new Map(
        settlements.map((s) => [
          s.id,
          {
            label: `${s.deposit.number} · ${s.deposit.tenant?.name ?? ''} · ${CURRENCY_SYMBOLS[s.deposit.currency] ?? ''}${Number(s.refundAmount.toString()).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
            depositId: s.depositId,
          },
        ]),
      );
      for (const m of mine) {
        if (m.documentType !== 'DEPOSIT_REFUND') continue;
        const found = label.get(m.documentId);
        m.documentLabel = found?.label ?? null;
        m.depositId = found?.depositId ?? null;
      }
    }
    return mine;
  }

  /** Inbox size — drives the sidebar badge. */
  async pendingCount(organizationId: string, userId: string): Promise<number> {
    return (await this.pending(organizationId, userId)).length;
  }

  /** Opens the next round for a document, tolerating a concurrent opener. */
  private async openRound(workflowId: string, documentType: string, documentId: string, tx?: Prisma.TransactionClient) {
    const db = this.db(tx);
    const last = await db.approvalInstance.findFirst({
      where: { documentType, documentId },
      orderBy: { round: 'desc' },
      select: { round: true },
    });
    const include = { actions: true, workflow: { include: { steps: true } } };
    try {
      return await db.approvalInstance.create({
        data: { workflowId, documentType, documentId, round: (last?.round ?? 0) + 1, currentStep: 1 },
        include,
      });
    } catch (err) {
      // A concurrent caller won the unique constraint — adopt its round instead
      // of creating a duplicate.
      if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
        return db.approvalInstance.findFirstOrThrow({
          where: { documentType, documentId },
          orderBy: { round: 'desc' },
          include,
        });
      }
      throw err;
    }
  }

  private async latestLive(documentType: string, documentId: string) {
    return this.prisma.approvalInstance.findFirst({
      where: { documentType, documentId, cancelledAt: null },
      orderBy: { round: 'desc' },
      include: { actions: true, workflow: { include: { steps: true } } },
    });
  }

  /** Approval is a stage of the debit-note lifecycle, so a settled round moves
   * the invoice itself. Other document types gate at their own action (a deposit
   * refund re-checks gate() when it is paid) and need no write here. */
  private async syncDocumentStatus(
    tx: Prisma.TransactionClient,
    documentType: string,
    documentId: string,
    status: ApprovalStatus,
  ): Promise<void> {
    if (documentType !== 'INVOICE') return;
    if (status === 'APPROVED') {
      await tx.invoice.updateMany({ where: { id: documentId, status: 'PENDING_APPROVAL' }, data: { status: 'APPROVED' } });
    } else if (status === 'REJECTED') {
      // Back to DRAFT so it can be corrected and re-submitted; the rejected round
      // stays on file as history.
      await tx.invoice.updateMany({ where: { id: documentId, status: 'PENDING_APPROVAL' }, data: { status: 'DRAFT' } });
    }
  }

  private async isActor(tx: Prisma.TransactionClient, step: ApprovalStep, userId: string): Promise<boolean> {
    if (step.actorType === 'USER') return step.actorUserId === userId;
    if (step.actorType === 'ROLE') {
      if (!step.actorRoleId) return false;
      const ur = await tx.userRole.findFirst({ where: { userId, roleId: step.actorRoleId } });
      return Boolean(ur);
    }
    return false;
  }
}

function deriveStatus(inst: { isComplete: boolean; cancelledAt: Date | null; actions: { action: string }[] }): ApprovalStatus {
  if (inst.cancelledAt) return 'CANCELLED';
  if (inst.actions.some((a) => a.action === 'REJECT')) return 'REJECTED';
  return inst.isComplete ? 'APPROVED' : 'PENDING';
}
