import type * as Hapi from "@hapi/hapi";
import AuthBearer from "hapi-auth-bearer-token";
import { IAppConfig } from "@digiresilience/metamigo-config";
import { IMetamigoRepositories } from "@digiresilience/metamigo-common";

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

  server.auth.strategy("session-id-bearer-token", "bearer-access-token", {
    allowQueryToken: false,
    validate: async (
      request: Hapi.Request,
      token: string,
      h: Hapi.ResponseToolkit
    ) => {
      const repos = request.db() as IMetamigoRepositories;
      const session = await repos.sessions.findBy({ sessionToken: token });
      const isValid = !!session;
      if (!isValid) return { isValid, credentials: {} };
      const user = await repos.users.findById({ id: session.userId });
      const credentials = { sessionToken: token, user };
      return { isValid, credentials };
    },
  });
};
