/**
 * API endpoint to send a notification to all users
 *
 * Only super admins can send notifications to all users.
 */

import { requireSuperAdmin } from '../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'
import { sendNotification } from '../../utils/notifications'
import { useDB, eq, and } from '../../utils/database'
import { user } from '../../database/schema'

interface NotifyAllRequest {
  message: string
  url?: string
}

interface NotifyAllResponse {
  success: boolean
  sentCount: number
  failedCount: number
  totalUsers: number
}

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

    const { message, url = '/dashboard' } = body

    // Validate required fields
    if (!message || message.trim().length === 0) {
      throw ApiErrors.validationError('Message is required')
    }

    if (message.length > 1000) {
      throw ApiErrors.validationError('Message must be 1000 characters or less')
    }

    // Get all active users (non-banned, non-super-admin)
    const db = useDB()
    const allUsers = await db
      .select({
        id: user.id,
        name: user.name,
        email: user.email,
        image: user.image
      })
      .from(user)
      .where(
        and(
          eq(user.banned, false),
          eq(user.superAdmin, false)
        )
      )

    const totalUsers = allUsers.length

    if (totalUsers === 0) {
      return createSuccessResponse<NotifyAllResponse>({
        success: true,
        sentCount: 0,
        failedCount: 0,
        totalUsers: 0
      }, 'No users to notify')
    }

    // Send notification to each user
    let sentCount = 0
    let failedCount = 0

    await Promise.allSettled(
      allUsers.map(async (user) => {
        try {
          await sendNotification({
            userId: user.id,
            senderName: session.user.name || 'Admin',
            senderEmail: session.user.email,
            senderAvatar: session.user.image || undefined,
            body: message.trim(),
            url
          })
          sentCount++
        } catch (error) {
          console.error(`[notify-all] Failed to send notification to user ${user.id}:`, error)
          failedCount++
        }
      })
    )

    return createSuccessResponse<NotifyAllResponse>({
      success: true,
      sentCount,
      failedCount,
      totalUsers
    }, `Notification sent to ${sentCount} out of ${totalUsers} users`)
  } catch (error) {
    throw handleApiError(error)
  }
})
