/**
 * Test endpoint to send push notifications manually
 * Use this to test if push notifications work in background
 *
 * Usage: POST /api/push/test
 * Body: { roleIds?: number[] } (optional, defaults to all roles)
 */

import { sendPushToRoles } from '../../utils/pushNotifier'

export default defineEventHandler(async (event) => {
  try {
    // Verify user is authenticated
    const token = await getTokenHelper(event)
    if (!token) {
      return { success: false, error: 'Unauthorized' }
    }

    // Get role IDs from request body or use current user's role
    const body = await readBody(event).catch(() => ({}))
    const tokenPayload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString())
    const roleIds = body?.roleIds || [tokenPayload.AD_Role_ID]

    console.log('[Push Test] Sending test notification to roles:', roleIds)

    // Send test push notification
    const result = await sendPushToRoles(roleIds, {
      title: '🧪 Test Push Notification',
      body: 'This is a test notification to verify background push delivery',
      icon: '/favicon.ico',
      badge: '/favicon.ico',
      url: '/sales/orders',
      data: {
        type: 'test',
        timestamp: Date.now()
      }
    })

    return {
      success: true,
      message: 'Test notification sent',
      result
    }
  } catch (error: any) {
    console.error('[Push Test] Error:', error)
    return {
      success: false,
      error: error.message
    }
  }
})
