const nocache = require('nocache');

module.exports = {
  init(server, node, opts) {
    const prefix = `${opts.prefix}/api/did/session`;

    const handler = async (req, res) => {
      if (!req.user) {
        res.json({ user: null });
        return;
      }

      const user = { ...req.user };
      if (user.role) {
        const teamDid = req.getBlockletDid();
        // FIXME: this code may have performance issue
        const rbac = await node.getRBAC(teamDid);
        user.permissions = await rbac.getScope(req.user.role);
      }

      res.json({ user });
    };

    server.get(prefix, nocache(), handler);
    server.post(prefix, nocache(), handler);
  },
};
