const get = require('lodash/get');
const { joinURL } = require('ufo');
const { NODE_SERVICES, WELLKNOWN_SERVICE_PATH_PREFIX } = require('@abtnode/constant');
const { BLOCKLET_CONFIGURABLE_KEY } = require('@blocklet/constant');
const { getDidDomainForBlocklet } = require('@abtnode/util/lib/get-domain-for-blocklet');

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

      const [blockletInfo, blocklet, serviceConfig, info] = await Promise.all([
        req.getBlockletInfo(),
        req.getBlocklet(),
        req.getServiceConfig(NODE_SERVICES.AUTH),
        req.getNodeInfo(),
      ]);
      const pathPrefix = req.headers['x-path-prefix'] || '/';
      const groupPathPrefix = req.headers['x-group-path-prefix'];

      const passportColor = get(
        (blocklet.environments || []).find((x) => x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_PASSPORT_COLOR),
        'value',
        'auto'
      );

      const serverPort = info.routing?.httpsPort && info.routing?.httpsPort !== 443 ? `:${info.routing.httpsPort}` : '';
      const serverEndpoint = joinURL(
        `https://${getDidDomainForBlocklet({ did: info.did })}${serverPort}`,
        info.routing?.adminPath || '/'
      );
      const isSessionHardeningEnabled = blocklet?.settings?.enableSessionHardening;

      res.send(`window.env = {
  did: "${blockletInfo.did}",
  appId: "${blocklet.appDid}",
  appName: "${blockletInfo.name}",
  pathPrefix: "${pathPrefix}",
  apiPrefix: "${pathPrefix.replace(/\/+$/, '')}${WELLKNOWN_SERVICE_PATH_PREFIX}",
  ${groupPathPrefix ? `groupPathPrefix: "${groupPathPrefix}",` : ''}
  webWalletUrl: "${info.webWalletUrl || serviceConfig.webWalletUrl || opts.webWalletUrl}",
  nftDomainUrl: "${info.nftDomainUrl || ''}",
  passportColor: "${passportColor}",
  serverDid: "${info.did}",
  enableDocker: "${info.enableDocker}",
  enableDockerNetwork: "${info.enableDockerNetwork}",
  serverEndpoint: "${serverEndpoint}",
  serverVersion: "${info.version}",
  mode: "${info.mode}",
  enableSessionHardening: ${isSessionHardeningEnabled || false},
  ownerNft: ${JSON.stringify(info.ownerNft || '')},
  launcher: ${JSON.stringify(info.launcher || '')},
  runtimeConfig: {
    blockletMaxMemoryLimit: ${info.runtimeConfig?.blockletMaxMemoryLimit},
    daemonMaxMemoryLimit: ${info.runtimeConfig?.daemonMaxMemoryLimit},
  },
  gateway: {
    wafPolicy: {
      enabled: ${info?.routing?.wafPolicy?.enabled},
    },
  }
}`);
    });
  },
};
