/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
const get = require('lodash/get');
const logger = require('@abtnode/logger')(require('../../package.json').name);

module.exports = {
  init(server, node, opts) {
    server.get(`${opts.prefix}/blocklet/logo/:did`, async (req, res) => {
      const staticDir = path.resolve(__dirname, './build');
      const sendOptions = { maxAge: '1d' };

      let blocklet = null;
      try {
        blocklet = await node.ensureBlockletIntegrity(req.params.did);

        if (blocklet && get(blocklet, 'env.appDir') && blocklet.meta.logo) {
          const logoFile = path.join(get(blocklet, 'env.appDir'), blocklet.meta.logo);

          if (fs.existsSync(logoFile)) {
            res.sendFile(logoFile, sendOptions);
            return;
          }
        }

        res.sendFile('/images/blocklet.png', { root: staticDir, ...sendOptions });
      } catch (err) {
        logger.error('failed to send blocklet logo', { did: req.params.did, error: err });
        res.sendFile('/images/blocklet.png', { root: staticDir, ...sendOptions });
      }
    });
  },
};
