/**
 * Generate Pusher Beams authentication token
 * POST /api/push/auth
 *
 * This endpoint is called by the Pusher Beams SDK on the client
 * to authenticate the user for receiving targeted push notifications.
 */

import { generateBeamsToken, isBeamsConfigured } from '../../services/pushNotifications'

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

    if (!isBeamsConfigured()) {
      throw createError({
        statusCode: 503,
        statusMessage: 'Push notifications are not configured'
      })
    }

    // Generate Beams token for this user
    const beamsToken = generateBeamsToken(userId)

    return beamsToken
  } catch (error: unknown) {
    console.error('[Push] Error generating Beams token:', error)

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

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