import { z } from 'zod';
import { sumCents } from '../money-util';
import { router, withPermission } from '../trpc';

export const depositsRouter = router({
  list: withPermission('deposit.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.deposit.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ createdAt: 'desc' }],
      include: { allocations: { select: { amount: true } }, sourceInvoice: { select: { number: true } } },
    });
    const tenantIds = [...new Set(rows.map((d) => d.tenantId))];
    const tenants = await ctx.prisma.tenant.findMany({ where: { id: { in: tenantIds } }, select: { id: true, name: true } });
    const nameOf = new Map(tenants.map((t) => [t.id, t.name]));
    // A settled deposit's refund may still be awaiting payout — surface it so the
    // row can offer "pay refund". (Latest settlement wins if there is more than one.)
    const settledIds = rows.filter((d) => d.status === 'SETTLED').map((d) => d.id);
    const settlements = settledIds.length
      ? await ctx.prisma.depositSettlement.findMany({
          where: { depositId: { in: settledIds } },
          orderBy: { createdAt: 'asc' },
          select: { depositId: true, refundAmount: true, refundedAt: true },
        })
      : [];
    const refundOf = new Map(
      settlements.map((s) => [s.depositId, { amount: s.refundAmount.toString(), pending: !s.refundedAt && Number(s.refundAmount) > 0 }]),
    );
    return rows.map((d) => {
      // Terminal deposits (applied/settled/refunded/void) hold nothing; for open
      // ones remaining = amount − allocations. (Settlement charges/refunds drain
      // the ledger without allocation rows, so don't derive those from allocations.)
      const open = d.status === 'HELD' || d.status === 'PARTIALLY_APPLIED';
      const allocated = sumCents(d.allocations);
      const remaining = open ? sumCents([{ amount: d.amount.toString() }, { amount: `-${allocated}` }]) : '0.00';
      return {
        id: d.id,
        number: d.number,
        status: d.status,
        currency: d.currency,
        tenantId: d.tenantId,
        tenantName: nameOf.get(d.tenantId) ?? '—',
        amount: d.amount.toString(),
        remaining,
        receivedDate: d.receivedDate,
        sourceInvoiceNumber: d.sourceInvoice?.number ?? null,
        refundPending: refundOf.get(d.id)?.pending ?? false,
        refundAmount: refundOf.get(d.id)?.amount ?? null,
      };
    });
  }),

  /** Invoices a deposit can be applied to (its tenant's unpaid ones). */
  applicableInvoices: withPermission('deposit.read')
    .input(z.object({ depositId: z.string() }))
    .query(async ({ ctx, input }) => {
      const deposit = await ctx.prisma.deposit.findFirst({
        where: { id: input.depositId, organizationId: ctx.organizationId ?? undefined },
        select: { tenantId: true, currency: true },
      });
      if (!deposit) return [];
      // Only same-currency invoices are applicable (cross-currency apply is rejected).
      const invoices = await ctx.prisma.invoice.findMany({
        where: { lease: { tenantId: deposit.tenantId }, currency: deposit.currency, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
        orderBy: { dueDate: 'asc' },
        include: { lines: { select: { amount: true } } },
      });
      return invoices.map((i) => ({ id: i.id, number: i.number, billingPeriod: i.billingPeriod, currency: i.currency, total: sumCents(i.lines) }));
    }),

  create: withPermission('deposit.create')
    .input(
      z.object({
        tenantId: z.string(),
        leaseId: z.string().optional(),
        amount: z.string().regex(/^\d+(\.\d{1,2})?$/),
        /** The deposit receipt number, when the office types its own. */
        number: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.deposits.create({
        number: input.number,
        organizationId: ctx.organizationId ?? '',
        tenantId: input.tenantId,
        leaseId: input.leaseId ?? null,
        amount: input.amount,
        receivedByUserId: ctx.user.id,
      }),
    ),

  allocate: withPermission('deposit.update')
    .input(z.object({ depositId: z.string(), invoiceId: z.string(), amount: z.string().regex(/^\d+(\.\d{1,2})?$/) }))
    .mutation(({ ctx, input }) =>
      ctx.deposits.apply({
        organizationId: ctx.organizationId ?? '',
        depositId: input.depositId,
        invoiceId: input.invoiceId,
        amount: input.amount,
        appliedByUserId: ctx.user.id,
      }),
    ),

  /** Move-out screen data: held balance + outstanding invoices + charge types. */
  /** Undo a manual application — the money goes back to the deposit and the
   *  balance back on the note. Same key as making one. */
  unapply: withPermission('deposit.update')
    .input(z.object({ allocationId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.deposits.unapply({
        organizationId: ctx.organizationId ?? '',
        allocationId: input.allocationId,
        reversedByUserId: ctx.user.id,
      });
      return { ok: true };
    }),

  /** What the refund approval looks like, without starting one. */
  refundApproval: withPermission('deposit.read')
    .input(z.object({ depositId: z.string() }))
    .query(({ ctx, input }) => ctx.deposits.refundApprovalState(ctx.organizationId ?? '', input.depositId, ctx.user.id)),

  /** Send it for approval — and send it again after a rejection, which is what
   *  makes a refused refund recoverable without unwinding the settlement. */
  submitRefundForApproval: withPermission('deposit.update')
    .input(z.object({ depositId: z.string() }))
    .mutation(({ ctx, input }) => ctx.deposits.submitRefundForApproval({ organizationId: ctx.organizationId ?? '', depositId: input.depositId })),

  settlementData: withPermission('deposit.read')
    .input(z.object({ depositId: z.string() }))
    .query(({ ctx, input }) => ctx.deposits.settlementData(ctx.organizationId ?? '', input.depositId)),

  /** Held deposits on ended/terminated leases that still need settling — so a
   * refund is never forgotten after move-out. */
  awaitingSettlement: withPermission('deposit.read').query(({ ctx }) =>
    ctx.deposits.awaitingSettlement(ctx.organizationId ?? ''),
  ),

  /** The itemised settlement statement, once settled. */
  settlement: withPermission('deposit.read')
    .input(z.object({ depositId: z.string() }))
    .query(({ ctx, input }) => ctx.deposits.getSettlement(ctx.organizationId ?? '', input.depositId)),

  settle: withPermission('deposit.update')
    .input(
      z.object({
        depositId: z.string(),
        arrears: z.array(z.object({ invoiceId: z.string(), amount: z.string().regex(/^\d+(\.\d{1,2})?$/) })).optional(),
        charges: z
          .array(z.object({ description: z.string().min(1), chargeTypeId: z.string(), amount: z.string().regex(/^\d+(\.\d{1,2})?$/) }))
          .optional(),
        note: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.deposits.settle({
        organizationId: ctx.organizationId ?? '',
        depositId: input.depositId,
        arrears: input.arrears,
        charges: input.charges,
        note: input.note ?? null,
        settledByUserId: ctx.user.id,
      }),
    ),

  /** Pay out a settled deposit's refund (records method/reference/who, posts
   * DR Refunds Payable / CR Bank, flips the deposit to REFUNDED). */
  disburseRefund: withPermission('deposit.update')
    .input(z.object({ depositId: z.string(), settlementMethodId: z.string().optional(), reference: z.string().optional() }))
    .mutation(({ ctx, input }) =>
      ctx.deposits.disburseRefund({
        organizationId: ctx.organizationId ?? '',
        depositId: input.depositId,
        settlementMethodId: input.settlementMethodId ?? null,
        reference: input.reference ?? null,
        disbursedByUserId: ctx.user.id,
      }),
    ),

  /** Undo a settlement whose refund hasn't been paid out yet — reverses the
   * accounting, re-opens the invoices and re-opens the deposit. */
  reverseSettlement: withPermission('deposit.update')
    .input(z.object({ depositId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.deposits.reverseSettlement({
        organizationId: ctx.organizationId ?? '',
        depositId: input.depositId,
        reversedByUserId: ctx.user.id,
      }),
    ),
});
