import * as redis from '../redis.js'
import { getLatestVersion } from '../version.js'
import { once } from '../util.js'
import { config } from '../config.js'
import { logger, timeSinceStartup } from '../logger.js'
import createError from 'http-errors'

const checkRedis = () => {
  if (redis.isEnabled()) {
    return redis.isReady()
  }
}

const checkLatestVersion = once(async function () {
  // config is required before the first version check
  await config.load()
  await getLatestVersion()
  logger.info(`[Health] Check latest version on startup. Time since startup: ${timeSinceStartup()}`)
})

async function healthy () {}

async function live () {}

async function ready () {
  await Promise.all([
    checkLatestVersion(),
    checkRedis()
  ])
}

export default async function healthPlugin (fastify, options) {
  fastify.decorate('probe', async (reply, func) => {
    try {
      await func()
      reply.send('')
    } catch (err) {
      throw createError(503)
    }
  })

  // TODO can be removed. is for compatibility with older helm charts
  fastify.get('/healthy', async (req, reply) => {
    await fastify.probe(reply, healthy)
  })

  fastify.get('/live', async (req, reply) => {
    await fastify.probe(reply, live)
  })

  fastify.get('/ready', async (req, reply) => {
    await fastify.probe(reply, ready)
  })
}