/**
 * Generate Pusher Beams authentication token
 * GET /api/push/auth?user_id=xxx
 *
 * This endpoint is called by the Pusher Beams SDK on the client
 * to authenticate the user for receiving targeted push notifications.
 *
 * The SDK sends a GET request with user_id as a query parameter.
 */

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

export default defineEventHandler(async (event) => {
  try {
    // Pusher Beams SDK sends user_id as query parameter
    const query = getQuery(event)
    const userIdFromQuery = query.user_id as string

    // Also try to get session for additional validation
    let sessionUserId: string | null = null
    try {
      const session = await requireUserSession(event)
      sessionUserId = session.user.id
    } catch {
      // Session might not be available if cookie wasn't passed correctly
      console.log('[Push] No session found, using user_id from query')
    }

    // Use query param user_id (required by Pusher SDK)
    const userId = userIdFromQuery

    if (!userId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'user_id query parameter is required'
      })
    }

    // Security check: if we have a session, make sure the user_id matches
    if (sessionUserId && sessionUserId !== userId) {
      console.warn('[Push] user_id mismatch:', { queryUserId: userId, sessionUserId })
      throw createError({
        statusCode: 403,
        statusMessage: 'User ID mismatch'
      })
    }

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

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

    console.log('[Push] Generated Beams token for user:', 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'
    })
  }
})
