import type * as Hapi from "@hapi/hapi";
import type { IInitOptions } from "pg-promise";
import Schmervice from "@hapipal/schmervice";
import { makePlugin } from "@digiresilience/hapi-pg-promise";

import type { IAppConfig } from "../../config";
import { dbInitOptions, IRepositories } from "@digiresilience/metamigo-db";
import { registerNextAuth } from "./hapi-nextauth.js";
import { registerSwagger } from "./swagger.js";
import { registerCloudflareAccessJwt } from "./cloudflare-jwt.js";
import { registerAuthBearer } from "./auth-bearer.js";
import pg from "pg-promise/typescript/pg-subset";

import { registerPostgraphile } from "./hapi-postgraphile.js";

export const register = async (
  server: Hapi.Server,
  config: IAppConfig
): Promise<void> => {
  await server.register(Schmervice);

  const pgpInit = dbInitOptions(config);
  const options = {
    // the only required parameter is the connection string
    connection: config.db.connection,
    // ... and the pg-promise initialization options
    pgpInit,
  };

  await server.register([
    {
      plugin: makePlugin<IInitOptions<IRepositories, pg.IClient>>(),
      options,
    },
  ]);

  await registerNextAuth(server, config);
  await registerSwagger(server);
  await registerCloudflareAccessJwt(server, config);
  await registerAuthBearer(server, config);
  await registerPostgraphile(server, config);
};
