/**
 * Device tokens table schema
 * Stores push notification device tokens for users
 */

import { pgTable, pgEnum, serial, text, timestamp, index } from 'drizzle-orm/pg-core'
import { relations } from 'drizzle-orm'
import { user } from './auth'

// Platform enum for device types
export const platformEnum = pgEnum('device_platform', ['android', 'ios', 'web'])

export const deviceTokens = pgTable('device_tokens', {
  id: serial('id').primaryKey(),
  userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),

  // Device token from FCM/APNs
  token: text('token').notNull(),

  // Platform type
  platform: platformEnum('platform').notNull(),

  // Optional device identifier for managing multiple devices
  deviceId: text('device_id'),

  // Timestamps
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at')
    .defaultNow()
    .$onUpdate(() => /* @__PURE__ */ new Date())
    .notNull()
}, table => ({
  userIdIdx: index('idx_device_tokens_user_id').on(table.userId),
  tokenIdx: index('idx_device_tokens_token').on(table.token)
}))

export const deviceTokensRelations = relations(deviceTokens, ({ one }) => ({
  user: one(user, {
    fields: [deviceTokens.userId],
    references: [user.id]
  })
}))

export type DeviceToken = typeof deviceTokens.$inferSelect
export type NewDeviceToken = typeof deviceTokens.$inferInsert
