/**
 * Register device token for push notifications
 * POST /api/push/register
 */

import { registerDeviceToken, type Platform } from '../../database/queries/deviceTokens'

const VALID_PLATFORMS: Platform[] = ['android', 'ios', 'web']

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)
    const userId = session.user.id

    const body = await readBody(event)

    // Validate token
    if (!body.token || typeof body.token !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Device token is required'
      })
    }

    // Validate platform
    if (!body.platform || !VALID_PLATFORMS.includes(body.platform)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Valid platform is required (android, ios, or web)'
      })
    }

    // Register the token
    const deviceToken = await registerDeviceToken(
      userId,
      body.token,
      body.platform as Platform,
      body.deviceId
    )

    return {
      success: true,
      deviceToken: {
        id: deviceToken.id,
        platform: deviceToken.platform
      }
    }
  } catch (error: unknown) {
    console.error('[Push] Error registering device token:', error)

    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }

    throw createError({
      statusCode: 500,
      statusMessage: error instanceof Error ? error.message : 'Failed to register device token'
    })
  }
})
