/**
 * API endpoint to send a notification to a specific user
 *
 * Only super admins can send notifications to other users.
 * Regular users can only send notifications to themselves (for testing).
 */

import { requireUserSession } from '../../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'
import { sendNotification } from '../../../utils/notifications'

interface SendNotificationRequest {
  targetUserId: string
  senderName?: string
  senderEmail?: string
  senderAvatar?: string
  notificationBody: string
  url: string
}

interface NotificationResponse {
  id: number
  userId: string
  senderName: string
  senderEmail: string | null
  senderAvatar: string | null
  body: string
  url: string
  unread: boolean
  createdAt: Date
}

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)
    const body = await readBody(event) as SendNotificationRequest

    const { targetUserId, senderName, senderEmail, senderAvatar, notificationBody, url } = body

    // Validate required fields
    if (!targetUserId || !notificationBody || !url) {
      throw ApiErrors.validationError('Missing required fields: targetUserId, notificationBody, url')
    }

    // Only super admins can send to other users
    // Regular users can only send to themselves (for testing)
    if (targetUserId !== session.user.id && !session.user.superAdmin) {
      throw ApiErrors.forbidden('Only super admins can send notifications to other users')
    }

    // Create the notification and notify the user via websocket
    const notification = await sendNotification({
      userId: targetUserId,
      senderName: senderName || session.user.name || 'System',
      senderEmail: senderEmail || session.user.email,
      senderAvatar: senderAvatar || session.user.image || undefined,
      body: notificationBody,
      url
    })

    return createSuccessResponse<NotificationResponse>(notification, 'Notification sent successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
