/**
 * user_2fa_backup_codes — auth-2fa.
 * One-time use backup codes for 2FA recovery (8 per enrollment).
 * Only SHA-256 hashes of plaintext codes are stored.
 */
import { pgTable, uuid, text, timestamp, index } from 'drizzle-orm/pg-core'
import { isNull } from 'drizzle-orm'
import { users } from './users'

export const user2faBackupCodes = pgTable(
  'user_2fa_backup_codes',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    codeHash: text('code_hash').notNull(), // SHA-256 hex of plaintext backup code
    // used_at NULL = unused
    usedAt: timestamp('used_at', { withTimezone: true }),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    // Partial index: unused codes only (WHERE used_at IS NULL)
    unusedCodesIdx: index('idx_2fa_backup_codes_user').on(t.userId).where(isNull(t.usedAt)),
  }),
)

export type User2faBackupCodeRow = typeof user2faBackupCodes.$inferSelect
export type NewUser2faBackupCode = typeof user2faBackupCodes.$inferInsert
