/**
 * user_trusted_devices — auth-2fa.
 * Remembered ("trusted") devices that bypass the 2FA challenge for 30 days.
 * The device trust token plaintext is set in an HttpOnly cookie;
 * only its SHA-256 hash is stored here.
 */
import { pgTable, uuid, text, timestamp, index } from 'drizzle-orm/pg-core'
import { users } from './users'
import { tenants } from './tenants'

export const userTrustedDevices = pgTable(
  'user_trusted_devices',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    tokenHash: text('token_hash').notNull().unique(), // SHA-256 hex of device trust token
    userAgent: text('user_agent'),                   // browser/OS for display
    ipAddress: text('ip_address'),                   // IP at trust time (informational)
    expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), // now() + 30 days
    // revoked_at NULL = active
    revokedAt: timestamp('revoked_at', { withTimezone: true }),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    userTenantIdx: index('idx_trusted_devices_user').on(t.userId, t.tenantId),
  }),
)

export type UserTrustedDeviceRow = typeof userTrustedDevices.$inferSelect
export type NewUserTrustedDevice = typeof userTrustedDevices.$inferInsert
