#!/usr/bin/env node
/*eslint-env node */
/*eslint-disable import/no-commonjs */

var jwt = require("jsonwebtoken");

var BASE_URL = "http://localhost:3000";
var METABASE_EMBED_SECRET_KEY = process.env["MB_EMBEDDING_SECRET_KEY"];

var resourceType = process.argv[2];
var resourceId = parseFloat(process.argv[3]);
var params = process.argv[4] ? JSON.parse(process.argv[4]) : {};

if (!METABASE_EMBED_SECRET_KEY || !resourceType || typeof resourceId !== "number" || isNaN(resourceId)) {
  process.stderr.write("USAGE: MB_EMBEDDING_SECRET_KEY=ABCD embed-sign <resource_type> <resource_id> [<params_json>]\n");
  process.exit(1);
}

var resource = {};
resource[resourceType] = resourceId;

var unsignedToken = {
  resource: resource,
  params: params
};

process.stderr.write(JSON.stringify(unsignedToken, null, 2) + "\n");

var signedToken = jwt.sign(unsignedToken, METABASE_EMBED_SECRET_KEY);

console.log(BASE_URL + "/embed/" + resourceType + "/" + signedToken);
