import { createRouter } from 'better-call';
import { defineDb } from '@btst/db';
export { toNodeHandler } from 'better-call/node';

function stack(config) {
  const { plugins, adapter, dbSchema, basePath } = config;
  const allRoutes = {};
  let betterDbSchema = dbSchema ?? defineDb({});
  for (const [pluginKey, plugin] of Object.entries(plugins)) {
    betterDbSchema = betterDbSchema.use(plugin.dbPlugin);
  }
  const adapterInstance = adapter(betterDbSchema);
  const context = {
    plugins,
    basePath,
    adapter: adapterInstance
  };
  for (const [pluginKey, plugin] of Object.entries(plugins)) {
    const pluginRoutes = plugin.routes(adapterInstance, context);
    for (const [routeKey, endpoint] of Object.entries(pluginRoutes)) {
      const compositeKey = `${pluginKey}_${routeKey}`;
      allRoutes[compositeKey] = endpoint;
    }
  }
  const pluginApis = {};
  for (const [pluginKey, plugin] of Object.entries(plugins)) {
    if (plugin.api) {
      pluginApis[pluginKey] = plugin.api(adapterInstance);
    }
  }
  const router = createRouter(allRoutes, {
    basePath
  });
  return {
    handler: router.handler,
    router,
    dbSchema: betterDbSchema,
    adapter: adapterInstance,
    api: pluginApis
  };
}

export { stack };
