import { Server } from "@hapi/hapi";
import { v4 as uuid } from "uuid";

interface RequestIdOptions {
  header?: string;
}

const register = async (
  server: Server,
  options?: RequestIdOptions
): Promise<void> => {
  const header = options?.header || "x-request-id";
  server.ext("onPreResponse", async (request, h) => {
    if (!request.response) {
      return h.continue;
    }

    if ("isBoom" in request.response) {
      const id = request.response.output.headers[header] || uuid();
      request.response.output.headers[header] = id;
    } else {
      const id = request.headers[header] || uuid();
      request.response.header(header, id);
    }

    return h.continue;
  });
};

const RequestIdPlugin = {
  register,
  name: "request-id",
  version: "0.0.1",
};

export default RequestIdPlugin;
