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

/*
 * The accounts the system posts to by itself: the bank, receivables, security
 * deposits held, refunds payable and tenant credit. Found by role, never by
 * code — every account carries the code the office has for it in their ERP, and
 * the office changes codes on the chart-of-accounts page.
 */

const LABEL: Record<GlAccountRole, string> = {
  BANK: 'Bank',
  RECEIVABLE: 'Accounts Receivable',
  DEPOSITS_HELD: 'Deposits Held',
  REFUNDS_PAYABLE: 'Refunds Payable',
  TENANT_CREDIT: 'Tenant Credit',
};

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

/** The organisation's account for a role, or null when it has none — for a
 *  read that shows nothing rather than fails. */
export function findSystemAccount(db: Db, organizationId: string, role: GlAccountRole): Promise<GlAccount | null> {
  return db.glAccount.findFirst({ where: { organizationId, role } });
}

/** The organisation's account for a role, for posting: refused when there is
 *  none, before anything is written. */
export async function systemAccount(db: Db, organizationId: string, role: GlAccountRole): Promise<GlAccount> {
  const account = await findSystemAccount(db, organizationId, role);
  if (!account) throw new BadRequestException(`The ${LABEL[role]} account is not set up in the chart of accounts`);
  return account;
}
