/*
 *
 * @copyright Copyright (c) OX Software GmbH, Germany <info@open-xchange.com>
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
 *
 * Any use of the work other than as authorized under this license or copyright law is prohibited.
 *
 */

import fastify from 'fastify'
import promClient from 'prom-client'
import fp from 'fastify-plugin'
import logger from '../logger.js'
import lightship from '../lightship.js'

import fastifyMetrics from 'fastify-metrics'

// This is a metrics server that exposes metrics to Prometheus on the /metrics endpoint on the METRICS_PORT
const app = fastify({ logger: false })
await app.get('/metrics', async (request, reply) => {
  reply
    .type(promClient.register.contentType)
    .send(await promClient.register.metrics())
})
try {
  // Binds and listens for connections on the specified host and port
  await app.listen({ host: '::', port: Number(process.env.METRICS_PORT) })
  logger.info(`Metrics Server listening on port ${process.env.METRICS_PORT}`)
} catch (err) {
  logger.error(err)
  await lightship.shutdown()
}

// This is a graceful shutdown handler for the metrics server
lightship.registerShutdownHandler(async () => {
  await logger.info('Metrics Server Shutting down...')
  if (app) await app.close()
})

// This plugin is used to expose metrics to Prometheus.
export default fp(async (fastify) => {
  await fastify.register(fastifyMetrics, {
    // do not expose metrics endpoint
    endpoint: null
  })
})