import { sql } from 'drizzle-orm'
import { bigint, check, index, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'

/** 1:1 opt-in extension of ledgerEntries (entryId → ledgerEntries.id; cross-package, no drizzle relation). */
export const ledgerEntryVesting = pgTable(
  'ledger_entry_vesting',
  {
    entryId: uuid('entry_id').primaryKey(),
    matureAt: timestamp('mature_at', { withTimezone: true }),
    sweptAt: timestamp('swept_at', { withTimezone: true }),
    withdrawableAt: timestamp('withdrawable_at', { withTimezone: true }),
  },
  (t) => [index('ledger_entry_vesting_mature_idx').on(t.matureAt).where(sql`${t.sweptAt} IS NULL`)],
)

/** 1:1 opt-in extension of walletBalances (ownerId logical-maps to walletBalances.ownerId — NO cross-package FK; plain text PK). */
export const walletVesting = pgTable(
  'wallet_vesting',
  {
    ownerId: text('owner_id').primaryKey(),
    pendingMinor: bigint('pending_minor', { mode: 'bigint' }).notNull().default(0n),
    maturedMinor: bigint('matured_minor', { mode: 'bigint' }).notNull().default(0n),
    withdrawableMinor: bigint('withdrawable_minor', { mode: 'bigint' }).notNull().default(0n),
    lifetimeEarnedMinor: bigint('lifetime_earned_minor', { mode: 'bigint' }).notNull().default(0n),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [
    check('wallet_vesting_pending_minor_nonneg', sql`${t.pendingMinor} >= 0`),
    check('wallet_vesting_matured_minor_nonneg', sql`${t.maturedMinor} >= 0`),
    check('wallet_vesting_withdrawable_minor_nonneg', sql`${t.withdrawableMinor} >= 0`),
  ],
)

export const vestingSchema = { ledgerEntryVesting, walletVesting }
export type VestingSchema = typeof vestingSchema
export type LedgerEntryVesting = typeof ledgerEntryVesting.$inferSelect
export type WalletVesting = typeof walletVesting.$inferSelect
