import Redis from 'ioredis'

let pub
let sub
let client

export const getValkeyClient = () => {
  if (!client) {
    const url = process.env.VALKEY_URL || 'redis://localhost:6379'
    client = new Redis(url)
  }
  return client
}

export const getValkeyPub = () => {
  if (!pub) {
    const url = process.env.VALKEY_URL || 'redis://localhost:6379'
    pub = new Redis(url)
  }
  return pub
}

export const getValkeySub = () => {
  if (!sub) {
    const url = process.env.VALKEY_URL || 'redis://localhost:6379'
    sub = new Redis(url)
  }
  return sub
}

export const publish = async (channel, data) => {
  const pubClient = getValkeyPub()
  const numReceivers = await pubClient.publish(channel, JSON.stringify(data))
  console.log(`[valkey] publish to ${channel} → ${numReceivers} receiver(s)`)
}

export const subscribe = (channel, callback) => {
  const subClient = getValkeySub()
  subClient.subscribe(channel)
  console.log(`[valkey] subscribed to ${channel}`)
  const handler = (ch, message) => {
    if (ch === channel) {
      console.log(`[valkey] received on ${channel}`)
      callback(JSON.parse(message))
    }
  }
  subClient.on('message', handler)
  return () => {
    subClient.unsubscribe(channel)
    subClient.removeListener('message', handler)
    console.log(`[valkey] unsubscribed from ${channel}`)
  }
}
