import {sendPushToUsers} from '../lib/push'
import {onceWithin} from '../lib/redis'
import {listTrailMembers} from './trails'

// push a trail update to its members minus the actor (and any explicit
// excludes). an optional redis throttle collapses bursts
export const notifyTrailMembers = async ({
  trail,
  actorId,
  body,
  throttle,
  excludeUserIds = [],
  members,
}: {
  trail: {id: string; name: string; authorId: string}
  actorId: string
  body: string
  throttle?: {key: string; ttlSeconds: number}
  excludeUserIds?: string[]
  members?: {id: string}[]
}): Promise<void> => {
  if (
    throttle &&
    !(await onceWithin(throttle.key, throttle.ttlSeconds))
  )
    return

  const recipients = members ?? (await listTrailMembers(trail))
  const skip = new Set([actorId, ...excludeUserIds])
  const recipientIds = recipients
    .map((m) => m.id)
    .filter((id) => !skip.has(id))
  if (!recipientIds.length) return

  await sendPushToUsers(recipientIds, (token) => ({
    to: token,
    title: trail.name,
    body,
    data: {trailId: trail.id},
  }))
}
