/**
 * Utility to notify super admins when a new user registers
 * Also sends a welcome message to the new user
 */

import { getSuperAdminUsers } from '../database/queries/users'
import { sendNotification } from './notifications'

interface NewUserData {
  id: string
  name?: string | null
  email: string
  image?: string | null
}

// Track notified users to prevent duplicate notifications
// Key: userId, Value: timestamp when notified
const notifiedUsers = new Map<string, number>()
const NOTIFICATION_WINDOW_MS = 60000 // 1 minute window to prevent duplicates

/**
 * Notify all super admins that a new user has registered
 * Also sends a welcome message to the new user
 * Call this function after any user creation (email, OAuth, etc.)
 * Includes deduplication to prevent multiple notifications for the same user
 */
export async function notifySuperAdminsOfNewUser(user: NewUserData): Promise<void> {
  try {
    // Check if we've already notified for this user recently
    const lastNotified = notifiedUsers.get(user.id)
    const now = Date.now()

    if (lastNotified && (now - lastNotified) < NOTIFICATION_WINDOW_MS) {
      console.log(`[notifySuperAdminsOfNewUser] Skipping duplicate notification for user ${user.id} (last notified ${now - lastNotified}ms ago)`)
      return
    }

    // Mark as notified
    notifiedUsers.set(user.id, now)

    // Clean up old entries (older than 5 minutes)
    for (const [userId, timestamp] of notifiedUsers.entries()) {
      if (now - timestamp > 300000) { // 5 minutes
        notifiedUsers.delete(userId)
      }
    }

    const superAdmins = await getSuperAdminUsers()

    // Notify super admins about the new user
    // Use Promise.allSettled() so individual failures don't prevent the welcome message from being sent
    await Promise.allSettled(
      superAdmins.map(async (admin) => {
        await sendNotification({
          userId: admin.id,
          senderName: user.name || 'New User',
          senderEmail: user.email,
          senderAvatar: user.image || undefined,
          body: 'registered on the platform',
          url: '/dashboard/admin'
        })
      })
    )

    // Send welcome message to the new user
    await sendNotification({
      userId: user.id,
      senderName: 'Welcome Team',
      senderEmail: undefined,
      senderAvatar: undefined,
      body: 'Welcome to the platform! We\'re excited to have you here. Get started by exploring your dashboard.',
      url: '/dashboard'
    }).catch((error: unknown) => {
      console.error('[notifySuperAdminsOfNewUser] Failed to send welcome message:', error)
      // Don't throw - welcome message failure shouldn't block the process
    })
  } catch (error) {
    console.error('Failed to create registration notifications:', error)
    // Don't throw error as this is not critical
  }
}
