import jose from "node-jose";
import * as jwt from "jsonwebtoken";

const generateKeystore = async () => {
  const keystore = jose.JWK.createKeyStore();
  await keystore.generate("oct", 256, {
    alg: "A256GCM",
    use: "enc",
  });
  await keystore.generate("oct", 256, {
    alg: "HS512",
    use: "sig",
  });
  return keystore;
};

const safeString = (input) =>
  Buffer.from(JSON.stringify(input)).toString("base64");

const stringify = (v) => JSON.stringify(v, undefined, 2);

const _generateJwks = async () => {
  const keystore = await generateKeystore();
  const encryption = keystore.all({ use: "enc" })[0].toJSON(true);
  const signing = keystore.all({ use: "sig" })[0].toJSON(true);

  return {
    nextAuth: {
      signingKeyB64: safeString(signing),
      encryptionKeyB64: safeString(encryption),
    },
  };
};

export const generateJwks = async (): Promise<void> => {
  console.log(stringify(await _generateJwks()));
};

export const createTokenForTesting = async (): Promise<void> => {
  const keys = await _generateJwks();
  const signingKey = Buffer.from(
    JSON.parse(
      Buffer.from(keys.nextAuth.signingKeyB64, "base64").toString("utf-8")
    ).k,
    "base64"
  );

  const token = jwt.sign(
    {
      iss: "Test Env",
      iat: 1606893960,
      aud: "metamigo",
      sub: "abel@guardianproject.info",
      name: "Abel Luck",
      email: "abel@guardianproject.info",
      userRole: "admin",
    },
    signingKey,
    { expiresIn: "100y", algorithm: "HS512" }
  );
  console.log("CONFIG");
  console.log(stringify(keys));
  console.log();
  console.log("TOKEN");
  console.log(token);
  console.log();
};
