import { BadRequestException } from '@nestjs/common';
import type { Prisma } from '@prisma/client';

/**
 * Resolves a settlement method for a money movement, refusing what should not
 * be recorded against it.
 *
 * Only the deposit refund path checked any of this. The two receipt paths wrote
 * `input.settlementMethodId ?? null` straight onto the row, so a payment could
 * be recorded against a deactivated method, or against a cheque with no cheque
 * number — the one thing that makes a cheque traceable later.
 *
 * Takes a transaction client so a caller inside $transaction validates against
 * the same snapshot it writes in.
 */
export async function assertSettlementMethod(
  db: Prisma.TransactionClient,
  settlementMethodId: string | null | undefined,
  reference: string | null | undefined,
): Promise<string | null> {
  if (!settlementMethodId) return null;
  const method = await db.settlementMethod.findFirst({ where: { id: settlementMethodId, isActive: true } });
  if (!method) throw new BadRequestException('Settlement method not found');
  if (method.requiresReference && !reference?.trim()) {
    throw new BadRequestException(`A reference is required for ${method.nameEn}`);
  }
  return method.id;
}
