/**
 * Unregister device token for push notifications
 * POST /api/push/unregister
 */

import { removeDeviceToken } from '../../database/queries/deviceTokens'

export default defineEventHandler(async (event) => {
  try {
    await requireUserSession(event)

    const body = await readBody(event)

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

    // Remove the token
    const removed = await removeDeviceToken(body.token)

    return {
      success: true,
      removed
    }
  } catch (error: unknown) {
    console.error('[Push] Error unregistering 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 unregister device token'
    })
  }
})
