import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router, withPermission } from '../trpc';

/**
 * How money arrives and leaves — cash, cheque, bank transfer, and whatever else
 * the office starts taking. Seeded, but a lookup a clerk should own: adding
 * PayMe or retiring a method used to mean editing seed.ts and re-running it.
 *
 * There is no delete, deliberately. Receipt.settlementMethodId is onDelete:
 * SetNull, so deleting one blanks how every historical payment was made, and
 * DepositSettlement.refundMethodId has no rule at all. Deactivating takes a
 * method out of the pickers while every record that names it still reads.
 */
const methodInput = z.object({
  nameEn: z.string().min(1).max(80),
  nameZh: z.string().max(80).optional().nullable(),
  requiresReference: z.boolean().default(false),
  /** Printed as "Remarks" on the receipt of every payment made this way. */
  receiptRemark: z.string().trim().max(500).optional().nullable().transform((v) => v || null),
  sortOrder: z.number().int().min(0).default(0),
  isActive: z.boolean().default(true),
});

export const settlementMethodsRouter = router({
  /** Every method, active or not — this is the management screen, not a picker. */
  list: withPermission('settlement-method.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.settlementMethod.findMany({ orderBy: [{ isActive: 'desc' }, { sortOrder: 'asc' }, { nameEn: 'asc' }] });
    // How many receipts already name each, so deactivating one is informed.
    const counts = await ctx.prisma.receipt.groupBy({
      by: ['settlementMethodId'],
      where: { organizationId: ctx.organizationId ?? undefined, settlementMethodId: { not: null } },
      _count: { _all: true },
    });
    const used = new Map(counts.map((c) => [c.settlementMethodId, c._count._all]));
    return rows.map((r) => ({
      id: r.id,
      code: r.code,
      nameEn: r.nameEn,
      nameZh: r.nameZh,
      requiresReference: r.requiresReference,
      receiptRemark: r.receiptRemark,
      sortOrder: r.sortOrder,
      isActive: r.isActive,
      receiptCount: used.get(r.id) ?? 0,
    }));
  }),

  create: withPermission('settlement-method.create')
    .input(methodInput.extend({ code: z.string().min(1).max(32) }))
    .mutation(async ({ ctx, input }) => {
      const code = input.code.trim().toUpperCase();
      const dup = await ctx.prisma.settlementMethod.findFirst({ where: { code }, select: { id: true } });
      // Checked rather than left to the unique index, so the caller gets a
      // sentence instead of a raw Prisma constraint message.
      if (dup) throw new TRPCError({ code: 'CONFLICT', message: 'A settlement method with that code already exists' });
      const { code: _ignored, ...rest } = input;
      const row = await ctx.prisma.settlementMethod.create({ data: { ...rest, code } });
      return { id: row.id };
    }),

  /** Code is not editable: it is what a record already written refers to. */
  update: withPermission('settlement-method.update')
    .input(methodInput.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...data } = input;
      const claimed = await ctx.prisma.settlementMethod.updateMany({ where: { id }, data });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Settlement method not found' });
      return { ok: true };
    }),

  setActive: withPermission('settlement-method.update')
    .input(z.object({ id: z.string(), isActive: z.boolean() }))
    .mutation(async ({ ctx, input }) => {
      const claimed = await ctx.prisma.settlementMethod.updateMany({ where: { id: input.id }, data: { isActive: input.isActive } });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Settlement method not found' });
      return { ok: true };
    }),
});
