import type { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';

type Db = Pick<Prisma.TransactionClient, 'glAccount'>;

/**
 * An account picked on a form — a charge's, a landlord's, a tenant's: one of
 * this organisation's, and active, unless it is the one the record already
 * has, so retiring an account never leaves the records naming it unsavable.
 * Undefined passes through (a partial update leaves it alone); blank is none.
 */
export async function pickedAccount(
  db: Db,
  organizationId: string,
  id: string | null | undefined,
  keep?: string | null,
): Promise<string | null | undefined> {
  if (id === undefined) return undefined;
  if (!id) return null;
  const account = await db.glAccount.findFirst({ where: { id, organizationId }, select: { id: true, isActive: true } });
  if (!account) throw new TRPCError({ code: 'NOT_FOUND', message: 'Account not found' });
  if (!account.isActive && account.id !== keep) throw new TRPCError({ code: 'BAD_REQUEST', message: 'This account is inactive' });
  return account.id;
}
