import { requireUserSession } from '../../../utils/auth'
import { markAllNotificationsAsRead } from '../../../database/queries/notifications'
import { handleApiError, createSuccessResponse } from '../../../utils/errors'
import { sendPusherEvent } from '../../../utils/pusher'

interface MarkAllReadResponse {
  marked: boolean
}

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

    // Emit real-time event to update the user's unread count
    try {
      sendPusherEvent(session.user.id, 'notification:read', {})
      sendPusherEvent(session.user.id, 'notification:unread-count', { count: 0 })
    } catch (error) {
      // Don't fail the request if real-time emission fails
      console.error('[Pusher] Failed to emit notification:read event:', error)
    }

    return createSuccessResponse<MarkAllReadResponse>({ marked: true }, 'All notifications marked as read')
  } catch (error) {
    throw handleApiError(error)
  }
})
