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

interface MarkReadResponse {
  notificationId: number
  read: boolean
}

export default eventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)
    const notificationId = Number(getRouterParam(event, 'id'))

    if (isNaN(notificationId)) {
      throw ApiErrors.validationError('Invalid notification ID')
    }

    const notification = await markNotificationAsRead(notificationId, session.user.id)

    if (!notification) {
      throw ApiErrors.notFound('Notification not found')
    }

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

    return createSuccessResponse<MarkReadResponse>({
      notificationId,
      read: true
    }, 'Notification marked as read')
  } catch (error) {
    throw handleApiError(error)
  }
})
