import isFunction from "lodash/isFunction.js";
import type * as Hapi from "@hapi/hapi";
import * as UserRoutes from "./users/index.js";
import * as VoiceRoutes from "./voice/index.js";
import * as WhatsappRoutes from "./whatsapp/index.js";
import * as SignalRoutes from "./signal/index.js";

const loadRouteIndex = async (server, index) => {
  const routes = [];
  for (const exported in index) {
    if (Object.prototype.hasOwnProperty.call(index, exported)) {
      const route = index[exported];
      routes.push(route);
    }
  }

  routes.forEach(async (route) => {
    if (isFunction(route)) server.route(await route(server));
    else server.route(route);
  });
};

export const register = async (server: Hapi.Server): Promise<void> => {
  // Load your routes here.
  // routes are loaded from the list of exported vars
  // a route file should export routes directly or an async function that returns the routes.
  loadRouteIndex(server, UserRoutes);
  loadRouteIndex(server, VoiceRoutes);
  loadRouteIndex(server, WhatsappRoutes);
  loadRouteIndex(server, SignalRoutes);
};
