import { EventEmitter } from 'events'

export type NotificationEvent = {
  type: string
  payload?: unknown
  createdAt?: string
}

type Client = {
  orgId: string
  send: (evt: NotificationEvent) => void
}

type RealtimeState = {
  emitter: EventEmitter
  clientsByOrg: Map<string, Set<Client>>
}

// Ensure singleton across hot reloads
const g = globalThis as unknown as { __REALTIME__?: RealtimeState }

if (!g.__REALTIME__) {
  g.__REALTIME__ = {
    emitter: new EventEmitter(),
    clientsByOrg: new Map(),
  }
}

export const realtime = g.__REALTIME__

export function addClient(orgId: string, client: Client) {
  if (!realtime.clientsByOrg.has(orgId)) {
    realtime.clientsByOrg.set(orgId, new Set())
  }
  realtime.clientsByOrg.get(orgId)!.add(client)
}

export function removeClient(orgId: string, client: Client) {
  const set = realtime.clientsByOrg.get(orgId)
  if (set) {
    set.delete(client)
    if (set.size === 0) {
      realtime.clientsByOrg.delete(orgId)
    }
  }
}

export function notifyOrganization(orgId: string, event: NotificationEvent) {
  const set = realtime.clientsByOrg.get(orgId)
  if (!set) return
  const payload: NotificationEvent = { ...event, createdAt: event.createdAt || new Date().toISOString() }
  for (const client of set) {
    try {
      client.send(payload)
    } catch {
      // Ignore send errors
    }
  }
}

export function notifyMany(orgIds: string[], event: NotificationEvent) {
  const unique = Array.from(new Set(orgIds.filter(Boolean)))
  for (const orgId of unique) {
    notifyOrganization(orgId, event)
  }
}

