import { Server, RouteOptionsAccess } from "@hapi/hapi";
import { Prometheus } from "@promster/hapi";
import { Counter } from "prom-client";

interface StatusOptions {
  path?: string;
  auth?: RouteOptionsAccess;
}

const count = (statusCounter: Counter) => async () => {
  statusCounter.inc();
  return "Incremented metamigo_status_test counter";
};

const ping = async () => "OK";

const statusRoutes = (server: Server, opt?: StatusOptions) => {
  const path = opt?.path || "/status";
  const statusCounter = new Prometheus.Counter({
    name: "metamigo_status_test",
    help: "Test counter",
  });

  return [
    {
      method: "GET",
      path: `${path}/ping`,
      handler: ping,
      options: {
        auth: opt?.auth,
        tags: ["api", "status", "ping"],
        description: "Returns 200 and OK as the response.",
      },
    },
    {
      method: "GET",
      path: `${path}/inc`,
      handler: count(statusCounter),
      options: {
        auth: opt?.auth,
        tags: ["api", "status", "prometheus"],
        description: "Increments a test counter, for testing prometheus.",
      },
    },
  ];
};

const register = async (
  server: Server,
  options: StatusOptions
): Promise<void> => {
  server.route(statusRoutes(server, options));
};

const StatusPlugin = {
  register,
  name: "status",
  version: "0.0.1",
};

export default StatusPlugin;
