const { WELLKNOWN_AUTH_PATH_PREFIX } = require('@abtnode/constant');

module.exports = {
  init(server, node, opts) {
    server.get(`**${opts.prefix}/api/env`, async (req, res) => {
      res.type('js');

      const [blocklet, config, info] = await Promise.all([
        req.getBlockletInfo(),
        req.getServiceConfig(opts.name),
        req.getNodeInfo(),
      ]);
      let pathPrefix = req.headers['x-path-prefix'] || '/';
      let groupPathPrefix = req.headers['x-group-path-prefix'];

      // fix pathPrefix && groupPathPrefix
      // FIXME: pathPrefix and groupPathPrefix should be correct in service gateway
      pathPrefix = pathPrefix.replace(WELLKNOWN_AUTH_PATH_PREFIX, '') || '/';
      if (groupPathPrefix) {
        groupPathPrefix = groupPathPrefix.replace(WELLKNOWN_AUTH_PATH_PREFIX, '') || '/';
      }

      res.send(`window.env = {
  appId: "${blocklet.did}",
  appName: "${blocklet.name}",
  pathPrefix: "${pathPrefix}",
  apiPrefix: "${pathPrefix.replace(/\/+$/, '')}${opts.prefix}",
  ${groupPathPrefix ? `groupPathPrefix: "${groupPathPrefix}",` : ''}
  webWalletUrl: "${info.webWalletUrl || config.webWalletUrl || opts.webWalletUrl}",
}`);
    });
  },
};
