import type { BankAccount, GlAccount, Prisma } from '@prisma/client';
import { systemAccount } from './system-accounts';

/*
 * Which of the chart's bank accounts money posts to. Each of the office's
 * collection accounts (BankAccount) names its own bank account in the chart; one
 * that names none posts to the chart's Bank (the BANK role), as everything did
 * before collection accounts had accounts of their own.
 *
 * A payment of a debit note went into the account printed on the note (frozen
 * on it at issue); a lease's deposits and prepayments arrive in, and its refunds
 * leave from, the lease's collection account. Either falls back to the
 * organisation's default collection account, as a note without one prints it.
 */

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

/** The account a note with no account of its lease's names: the organisation's
 *  default (collection agent), else its first active account by name. */
export function defaultCollectionAccount(db: Pick<Prisma.TransactionClient, 'bankAccount'>, organizationId: string): Promise<BankAccount | null> {
  return db.bankAccount.findFirst({
    where: { organizationId, isActive: true },
    orderBy: [{ isCollectionAgent: 'desc' }, { name: 'asc' }],
  });
}

/** The ledger account for money in or out of a collection account — its own,
 *  or the chart's Bank when it has none or there is no collection account. */
export async function bankLedgerAccount(db: Db, organizationId: string, bankAccountId: string | null): Promise<GlAccount> {
  const bank = bankAccountId
    ? await db.bankAccount.findFirst({ where: { id: bankAccountId, organizationId }, select: { glAccount: true } })
    : null;
  return bank?.glAccount ?? systemAccount(db, organizationId, 'BANK');
}

/** The ledger account of a lease's collection account — the bank its deposits
 *  and prepayments arrive in and its refunds leave from. No lease, or a lease
 *  naming no account, is the organisation's default collection account. */
export async function leaseBankLedgerAccount(db: Db, organizationId: string, leaseId: string | null): Promise<GlAccount> {
  const lease = leaseId ? await db.lease.findFirst({ where: { id: leaseId, organizationId }, select: { bankAccountId: true } }) : null;
  const bankAccountId = lease?.bankAccountId ?? (await defaultCollectionAccount(db, organizationId))?.id ?? null;
  return bankLedgerAccount(db, organizationId, bankAccountId);
}

/** The ledger account each note's payment posts to, by invoice id: the account
 *  printed on the note, or the default collection account for a note that went
 *  out with none. */
export async function noteBankLedgerAccounts(db: Db & Pick<Prisma.TransactionClient, 'invoice'>, organizationId: string, invoiceIds: readonly string[]): Promise<Map<string, GlAccount>> {
  const notes = await db.invoice.findMany({ where: { id: { in: [...new Set(invoiceIds)] }, organizationId }, select: { id: true, bankAccountId: true } });
  const fallback = notes.some((n) => !n.bankAccountId) ? ((await defaultCollectionAccount(db, organizationId))?.id ?? null) : null;
  const byBank = new Map<string | null, GlAccount>();
  const out = new Map<string, GlAccount>();
  for (const n of notes) {
    const bankAccountId = n.bankAccountId ?? fallback;
    if (!byBank.has(bankAccountId)) byBank.set(bankAccountId, await bankLedgerAccount(db, organizationId, bankAccountId));
    out.set(n.id, byBank.get(bankAccountId)!);
  }
  return out;
}
