const joinUrl = require('url-join');
const {
  createIssuePassportRequest,
  handleIssuePassportResponse,
  checkWalletVersion,
  beforeIssuePassportRequest,
} = require('@abtnode/auth/lib/auth');

module.exports = function createRoutes(node, authenticator, login, opts) {
  return {
    action: 'issue-passport',

    onStart: async ({ extraParams, req }) => {
      const { locale = 'en', id } = extraParams;
      const teamDid = req.headers['x-blocklet-did'];

      await beforeIssuePassportRequest({ node, teamDid, locale, id });
    },

    claims: {
      signature: async ({ extraParams, context: { request, abtwallet } }) => {
        const { id, locale } = extraParams;
        checkWalletVersion({ abtwallet, locale });
        const nodeInfo = await node.getNodeInfo();
        const teamDid = request.headers['x-blocklet-did'];

        return createIssuePassportRequest({
          node,
          nodeInfo,
          teamDid,
          id,
          locale,
        });
      },
    },

    onAuth: async ({ userDid, userPk, claims, extraParams, req, baseUrl }) => {
      const { locale, id } = extraParams;
      const nodeInfo = await node.getNodeInfo();
      const teamDid = req.headers['x-blocklet-did'];
      const statusEndpointBaseUrl = joinUrl(baseUrl, opts.prefix);
      const endpoint = baseUrl;

      return handleIssuePassportResponse({
        node,
        nodeInfo,
        teamDid,
        userDid,
        userPk,
        id,
        locale,
        claims,
        statusEndpointBaseUrl,
        endpoint,
      });
    },
  };
};
