'use strict';

var Keypairs = require('./keypairs.js');
var Keyfetch = require('keyfetch');

Keypairs.generate().then(function (keypair) {
  return Keypairs.thumbprint({ jwk: keypair.public }).then(function (thumb) {
    var iss = 'https://coolaj86.com/';

    // shim so that no http request is necessary
    keypair.private.kid = thumb;
    Keyfetch._setCache(iss, { thumbprint: thumb, jwk: keypair.private });

    return Keypairs.signJwt({
      jwk: keypair.private
    , claims: {
        iss: iss
      , sub: 'coolaj86@gmail.com'
      , exp: Math.round(Date.now()/1000) + (3 * 24 * 60 * 60)
      }
    });
  });
}).then(function (jwt) {
  console.log(jwt);
  return Keyfetch.verify({ jwt: jwt }).then(function (ok) {
    if (!ok) {
      throw new Error("SANITY: did not verify (should have failed)");
    }
    console.log("Verified token");
  });
}).catch(function (err) {
  console.error(err);
});