import {createClient} from 'redis'

import {env} from '../env'

export const redis = createClient({url: env.REDIS_URL})

redis.on('error', (err) => {
  console.error('redis error', err)
})

await redis.connect()

// true only for the first call under this key within the window; a redis
// hiccup counts as "not first" so callers throttle rather than burst
export const onceWithin = async (
  key: string,
  ttlSeconds: number,
): Promise<boolean> => {
  const first = await redis
    .set(key, '1', {NX: true, EX: ttlSeconds})
    .catch((err: unknown) => {
      console.error('redis throttle unavailable', {key, err})
      return null
    })
  return first != null
}
