import type { Querier } from '@platform-modules/db'
import { ledgerEntries } from './schema.js'
import type { LedgerSchema } from './schema.js'
import type { AppendEntryInput, AppendEntryResult } from './types.js'

export async function appendEntry<S extends LedgerSchema>(
  tx: Querier<S>,
  input: AppendEntryInput,
): Promise<AppendEntryResult> {
  const rows = await tx
    .insert(ledgerEntries)
    .values({
      delta: input.delta,
      currency: input.currency ?? null,
      reason: input.reason,
      ref: input.ref ?? null,
      idempotencyKey: input.key,
    })
    .onConflictDoNothing({ target: ledgerEntries.idempotencyKey })
    .returning({ id: ledgerEntries.id })

  return { inserted: rows.length > 0, id: rows[0]?.id ?? null }
}
