const { verify, getVerifyData } = require('@blocklet/sdk/lib/util/verify-sign');
const logger = require('../libs/logger')('blocklet-services:verify-sig');

const verifySig = async (req, res, next) => {
  try {
    const blocklet = await req.getBlocklet();
    const { data, sig } = getVerifyData(req, 'blocklet');

    if (!sig) {
      res.status(400).json({ error: 'Bad Request' });
      return;
    }

    const verified = await verify(data, sig, {
      // NOTICE: blocklet-service 的运行环境中不包含以下环境变量，必须从 blocklet 信息中去获取并传递
      type: blocklet.environmentObj.BLOCKLET_APP_CHAIN_TYPE,
      // Compatible with previous version where APP_ASK does not exist
      appSk: blocklet.environmentObj.BLOCKLET_APP_ASK || blocklet.environmentObj.BLOCKLET_APP_SK,
    });
    if (!verified) {
      logger.error('verify sig failed', { data, sig });
      res.status(401).json('verify sig failed');
      return;
    }
  } catch (error) {
    logger.error('verify sig failed', { error });
    res.status(401).json('verify sig failed');
    return;
  }
  next();
};

module.exports = verifySig;
