import {
  bigint,
  jsonb,
  pgTable,
  text,
  timestamp,
  uniqueIndex,
  uuid,
} from 'drizzle-orm/pg-core'

export const ledgerEntries = pgTable(
  'ledger_entries',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    delta: bigint('delta', { mode: 'bigint' }).notNull(),
    currency: text('currency'),
    reason: text('reason').notNull(),
    ref: jsonb('ref').$type<Record<string, unknown> | null>(),
    idempotencyKey: text('idempotency_key').notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [uniqueIndex('ledger_entries_idempotency_key_uq').on(table.idempotencyKey)],
)

/** Optional default balance projection — hosts may use their own column instead. */
export const walletBalances = pgTable('wallet_balances', {
  ownerId: text('owner_id').primaryKey(),
  balance: bigint('balance', { mode: 'bigint' }).notNull().default(0n),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})

export const ledgerSchema = {
  ledgerEntries,
  walletBalances,
}

export type LedgerSchema = typeof ledgerSchema
