import { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { awaitingReview } from '../../payments/awaiting-review';
import { router, staffProcedure, withPermission } from '../trpc';

const DOCUMENT_TYPES = ['INVOICE', 'DEPOSIT_REFUND'];

const stepInput = z.object({
  name: z.string().min(1),
  actorType: z.enum(['ROLE', 'USER']),
  actorRoleId: z.string().optional().nullable(),
  actorUserId: z.string().optional().nullable(),
});

export const approvalsRouter = router({
  // ── Config (admin) ─────────────────────────────────────────
  formData: withPermission('approval-workflow.read').query(async ({ ctx }) => {
    const [roles, users] = await Promise.all([
      ctx.prisma.role.findMany({ orderBy: { name: 'asc' }, select: { id: true, code: true, name: true } }),
      ctx.prisma.user.findMany({ where: { deletedAt: null, tenantId: null }, orderBy: { name: 'asc' }, select: { id: true, name: true } }),
    ]);
    return { roles, users, documentTypes: DOCUMENT_TYPES };
  }),

  workflows: withPermission('approval-workflow.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.approvalWorkflow.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ documentType: 'asc' }, { name: 'asc' }],
      include: { steps: { orderBy: { stepOrder: 'asc' } } },
    });
    return rows.map((w) => ({
      id: w.id,
      documentType: w.documentType,
      code: w.code,
      name: w.name,
      minAmount: w.minAmount ? w.minAmount.toFixed(2) : null,
      isActive: w.isActive,
      steps: w.steps.map((s) => ({
        stepOrder: s.stepOrder,
        name: s.name,
        actorType: s.actorType,
        actorRoleId: s.actorRoleId,
        actorUserId: s.actorUserId,
      })),
    }));
  }),

  upsertWorkflow: withPermission('approval-workflow.update')
    .input(
      z.object({
        id: z.string().optional(),
        documentType: z.string().min(1),
        code: z.string().min(1),
        name: z.string().min(1),
        minAmount: z.string().regex(/^\d+(\.\d{1,2})?$/).optional().nullable(),
        isActive: z.boolean().default(true),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const data = {
        documentType: input.documentType,
        code: input.code,
        name: input.name,
        minAmount: input.minAmount ?? null,
        isActive: input.isActive,
      };
      try {
        if (input.id) {
          await ctx.prisma.approvalWorkflow.update({ where: { id: input.id }, data });
          return { id: input.id };
        }
        const created = await ctx.prisma.approvalWorkflow.create({ data: { organizationId, ...data } });
        return { id: created.id };
      } catch (err) {
        if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
          throw new TRPCError({ code: 'CONFLICT', message: 'A workflow with that document type + code already exists' });
        }
        throw err;
      }
    }),

  /** Replace all steps of a workflow (ordered by array position). */
  setSteps: withPermission('approval-workflow.update')
    .input(z.object({ workflowId: z.string(), steps: z.array(stepInput).min(1) }))
    .mutation(async ({ ctx, input }) => {
      const wf = await ctx.prisma.approvalWorkflow.findFirst({
        where: { id: input.workflowId, organizationId: ctx.organizationId ?? undefined },
      });
      if (!wf) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workflow not found' });
      // Refuse to re-shape steps while approvals are mid-flight — that would
      // strand an instance whose currentStep no longer maps to a step. A
      // superseded round is not in flight; nobody can act on it any more.
      const inFlight = await ctx.prisma.approvalInstance.findFirst({
        where: { workflowId: input.workflowId, isComplete: false, cancelledAt: null },
      });
      if (inFlight) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message: 'This workflow has in-flight approvals — finish or reject them before changing its steps.',
        });
      }
      for (const s of input.steps) {
        if (s.actorType === 'ROLE' && !s.actorRoleId) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Pick a role for each role step' });
        if (s.actorType === 'USER' && !s.actorUserId) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Pick a user for each user step' });
      }
      await ctx.prisma.$transaction([
        ctx.prisma.approvalStep.deleteMany({ where: { workflowId: input.workflowId } }),
        ctx.prisma.approvalStep.createMany({
          data: input.steps.map((s, i) => ({
            workflowId: input.workflowId,
            stepOrder: i + 1,
            name: s.name,
            actorType: s.actorType,
            actorRoleId: s.actorType === 'ROLE' ? s.actorRoleId ?? null : null,
            actorUserId: s.actorType === 'USER' ? s.actorUserId ?? null : null,
          })),
        }),
      ]);
      return { ok: true };
    }),

  deleteWorkflow: withPermission('approval-workflow.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const used = await ctx.prisma.approvalInstance.findFirst({ where: { workflowId: input.id } });
      if (used) throw new TRPCError({ code: 'BAD_REQUEST', message: 'This workflow has approval history — deactivate it instead of deleting.' });
      await ctx.prisma.approvalWorkflow.deleteMany({ where: { id: input.id, organizationId: ctx.organizationId ?? undefined } });
      return { ok: true };
    }),

  // ── Inbox / acting (any back-office login; per-step actor enforced) ───────
  pending: staffProcedure.query(({ ctx }) =>
    ctx.approvals.pending(ctx.organizationId ?? '', ctx.user.id),
  ),

  /** The sidebar's live counts, keyed by nav item: this user's inbox, and the
   *  payments waiting on anyone who may approve them — which are in that inbox
   *  too. Cheap enough to re-read on every navigation. */
  badges: staffProcedure.query(async ({ ctx }) => {
    const signOffs = await ctx.approvals.pendingCount(ctx.organizationId ?? '', ctx.user.id);
    if (!ctx.user.permissions.includes('receipt.update')) return { myApprovals: signOffs, receipts: 0, depositReceipts: 0 };
    const byKind = await ctx.prisma.receipt.groupBy({
      by: ['kind'],
      where: awaitingReview(ctx.organizationId ?? undefined),
      _count: { _all: true },
    });
    const waiting = (kind: string) => byKind.find((g) => g.kind === kind)?._count._all ?? 0;
    const receipts = waiting('RECEIPT');
    const depositReceipts = waiting('DEPOSIT_RECEIPT');
    return { myApprovals: signOffs + receipts + depositReceipts, receipts, depositReceipts };
  }),

  /** Approving needs no words; refusing does. A rejection sends the note back to
   *  whoever raised it, and "rejected" with no reason is the thing that makes
   *  them walk over and ask — so the reason is required at the input, not left
   *  to the screen to remember. */
  act: staffProcedure
    .input(
      z
        .object({ instanceId: z.string(), action: z.enum(['APPROVE', 'REJECT']), note: z.string().optional() })
        .superRefine((v, ctx) => {
          if (v.action === 'REJECT' && !v.note?.trim()) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['note'], message: 'A reason is required to reject' });
          }
        }),
    )
    .mutation(({ ctx, input }) =>
      ctx.approvals.act({
        organizationId: ctx.organizationId ?? '',
        userId: ctx.user.id,
        instanceId: input.instanceId,
        action: input.action,
        note: input.note ?? null,
      }),
    ),
});
