"use strict";

var _tape = _interopRequireDefault(require("tape"));

var _milliseconds = _interopRequireDefault(require("milliseconds"));

var _reduxBundler = require("redux-bundler");

var _getSessionBundle = require("./get-session-bundle");

var _token = require("./token");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

const getRecentSessionValues = (date = Date.now()) => ({
  multiFactorLast: date.toString(),
  multiFactorAuthExp: (date + _milliseconds.default.days(30)).toString(),
  sessionRenewedAt: date.toString(),
  sessionExpiresAt: (date + _milliseconds.default.minutes(30)).toString()
});

const getStore = ({
  stubs,
  startingData,
  bundles
} = {}) => {
  global.document = {
    cookie: ''
  };
  global.location = {
    hostname: 'xchart.com',
    hash: ''
  };
  const store = (0, _reduxBundler.composeBundlesRaw)((0, _token.createTokenBundle)({
    name: 'token',
    domain: 'something.com'
  }), (0, _getSessionBundle.getSessionBundle)({
    activeOrgIdSelectorName: 'selectActiveOrgId',
    selectorsThatDetermineActivity: ['selectIsActive'],
    retryFailedFetchAfter: 1000
  }), _reduxBundler.appTimeBundle, _objectSpread({
    name: 'stubs',
    selectIsActive: () => true,
    selectActiveOrgId: () => null,
    selectShowUserLoading: () => false
  }, stubs), ...(bundles ? bundles : []))(startingData);
  return store;
};

(0, _tape.default)('getSessionBundle', async t => {
  const store = getStore({
    stubs: {
      selectActiveOrgId: () => 'cfd'
    }
  });
  t.equal(store.selectSessionOrgs(), null);
  store.doReceiveSession({
    multiFactorLast: '1628741741839',
    multiFactorAuthExp: '1631333741839',
    sessionRenewedAt: '1628741741839',
    sessionExpiresAt: '1628743541839',
    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ',
    orgs: [{
      id: 'cfd',
      roles: ['admin', 'provider'],
      status: null,
      memberId: '06a72fb5-c0c8-4949-89fb-4cf62289a828'
    }, {
      id: 'asdfasdfasdfasfasd',
      roles: ['admin', 'provider'],
      status: null,
      memberId: '8e5fb803-a062-418e-9969-c41307525393'
    }]
  });
  t.deepEqual(store.selectSessionOrgs(), [{
    id: 'asdfasdfasdfasfasd',
    roles: ['admin', 'provider'],
    status: null,
    memberId: '8e5fb803-a062-418e-9969-c41307525393'
  }, {
    id: 'cfd',
    roles: ['admin', 'provider'],
    status: null,
    memberId: '06a72fb5-c0c8-4949-89fb-4cf62289a828'
  }], 'should sort the orgs when receiving');
  t.deepEqual(store.selectSessionOrgIds(), ['asdfasdfasdfasfasd', 'cfd'], 'org Ids should exist');
  t.deepEqual(store.selectSessionRegularOrgIds(), ['asdfasdfasdfasfasd', 'cfd'], 'regular org Ids should be empty');
  t.equal(store.selectIsXchartUberUser(), false, 'xchart uber user should be false');
  t.deepEqual(store.selectActiveOrgMembership(), {
    id: 'cfd',
    roles: ['admin', 'provider'],
    status: null,
    memberId: '06a72fb5-c0c8-4949-89fb-4cf62289a828'
  }, 'should have active org membership');
  t.deepEqual(store.selectActiveOrgType(), 'regular', 'active org type is regular');
  t.equal(store.selectActiveOrgIsRegular(), true, 'active org is regular is true');
  t.equal(store.selectActiveOrgIsXchart(), false, 'active org is xhart is false');
  t.equal(store.selectActiveOrgIsParent(), false, 'active org is parent is false');
  t.end();
});
(0, _tape.default)('getSessionBundle no orgs', async t => {
  const store = getStore();
  t.equal(store.selectSessionOrgs(), null);
  store.doReceiveSession({
    multiFactorLast: '1628741741839',
    multiFactorAuthExp: '1631333741839',
    sessionRenewedAt: '1628741741839',
    sessionExpiresAt: '1628743541839',
    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ',
    orgs: null
  });
  t.deepEqual(store.selectSessionOrgs(), null, 'should have no orgs');
  t.deepEqual(store.selectSessionOrgIds(), [], 'org Ids should be empty');
  t.deepEqual(store.selectSessionRegularOrgIds(), [], 'regular org Ids should be empty');
  t.deepEqual(store.selectActiveOrgMembership(), null, 'should have no active org membership');
  t.equal(store.selectActiveOrgType(), null, 'active org type should be null');
  t.end();
});
(0, _tape.default)('getSessionBundle retry failed', t => {
  let gqlFetch;
  let keepAlive = true;
  const store = getStore({
    stubs: {
      selectAsyncActive: () => keepAlive,
      getExtraArgs: () => {
        return {
          gqlFetch: (...args) => gqlFetch(...args)
        };
      }
    },
    bundles: [(0, _reduxBundler.createReactorBundle)({
      idleTimeout: 100,
      stopWhenTabInactive: false
    })]
  });
  t.equal(store.selectSessionOrgs(), null);
  store.doReceiveSession(_objectSpread(_objectSpread({}, getRecentSessionValues(Date.now() - _milliseconds.default.minutes(4))), {}, {
    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ',
    orgs: null
  }));
  let testStart = Date.now();
  let calls = 0;
  let firstCall;

  gqlFetch = () => {
    calls++;

    if (calls === 1) {
      firstCall = Date.now();
    }

    if (calls === 1) {
      t.equal(store.selectSessionRaw().lastExtendError, null, 'it should now be a number');
      t.ok(firstCall - testStart < 200, 'first attempt to should be almost immediate');
      return Promise.reject('boom');
    }

    if (calls === 2) {
      t.equal(typeof store.selectSessionRaw().lastExtendError, 'number', 'it should now be a number');
      t.equal(store.selectSessionDataIsLoading(), true, 'session loading during re-try');
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            data: {
              extendSession: _objectSpread(_objectSpread({}, getRecentSessionValues()), {}, {
                token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ',
                orgs: null
              })
            }
          });
          setTimeout(() => {
            t.equal(store.selectSessionDataIsLoading(), false, 'after receiving session it should not be loading');
            t.end();
            keepAlive = false;
          });
        }, 500);
      });
    }

    if (calls === 3) {
      t.fail('should not get here');
    }
  };

  t.equal(store.selectSessionRaw().lastExtendError, null);
});
(0, _tape.default)('ensure proper persist actions', t => {
  const sb = (0, _getSessionBundle.getSessionBundle)({
    activeOrgIdSelectorName: 'selectActiveOrgId',
    selectorsThatDetermineActivity: ['selectIsActive'],
    persist: true
  });
  t.deepEqual(sb.persistActions, ['SESSION_RECEIVED']);
  const sb2 = (0, _getSessionBundle.getSessionBundle)({
    activeOrgIdSelectorName: 'selectActiveOrgId',
    selectorsThatDetermineActivity: ['selectIsActive']
  });
  t.deepEqual(sb2.persistActions, [], 'no persist actions if not specified');
  const sb3 = (0, _getSessionBundle.getSessionBundle)({
    activeOrgIdSelectorName: 'selectActiveOrgId',
    selectorsThatDetermineActivity: ['selectIsActive'],
    persist: false
  });
  t.deepEqual(sb3.persistActions, [], 'no persist actions if not specified');
  t.end();
});
(0, _tape.default)('auth status', t => {
  const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ';

  const getStoreWithToken = () => getStore({
    startingData: {
      token: {
        token
      }
    }
  });

  const storeWithNoToken = getStore();
  t.equal(storeWithNoToken.selectAuthStatus(), 'none', 'should start as none because no token');
  t.equal(storeWithNoToken.selectIsDeterminingAuthStatus(), false, 'is not determining');
  const storeWithToken = getStoreWithToken();
  t.equal(storeWithToken.selectHasAuthToken(), true, 'should have auth token to start');
  t.equal(storeWithToken.selectAuthStatus(), null, 'should start as null because still figuring it out');
  t.equal(storeWithToken.selectIsDeterminingAuthStatus(), true, 'is determining');
  t.equal(storeWithToken.selectNotFullyAuthenticated(), false, 'while we are determining "not fully authed" should be false');
  const store = getStoreWithToken();
  t.equal(store.selectHasAuthToken(), true, 'should have auth token to start');
  t.equal(store.selectAuthToken(), token);
  t.equal(store.selectAuthStatus(), null, 'should start as null because still figuring it out');
  t.equal(store.selectNotFullyAuthenticated(), false, 'while we are determining "not fully authed" should be false');
  t.equal(store.selectIsFullyAuthenticated(), false);
  store.doReceiveSession(_objectSpread(_objectSpread({}, getRecentSessionValues()), {}, {
    token,
    orgs: null
  }));
  t.equal(store.selectAuthStatus(), 'full');
  t.equal(store.selectIsFullyAuthenticated(), true);
  t.equal(store.selectNotFullyAuthenticated(), false, 'it is only not fully when we know for sure that we are');
  store.doReceiveSession(_objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, getRecentSessionValues()), {}, {
    multiFactorLast: null,
    multiFactorAuthExp: null
  })), {}, {
    token,
    orgs: null
  }));
  t.equal(store.selectAuthStatus(), 'partial');
  t.equal(store.selectNotFullyAuthenticated(), true, 'we are not fully authed if we are partial');
  const storeWithOldSession = getStoreWithToken();
  storeWithOldSession.doReceiveSession(_objectSpread(_objectSpread({}, _objectSpread({}, getRecentSessionValues(Date.now() - _milliseconds.default.days(30)))), {}, {
    token,
    orgs: null
  }));
  t.equal(storeWithOldSession.selectAuthStatus(), 'expired');
  t.end();
});
(0, _tape.default)('membership selectors', t => {
  const bundle = (0, _getSessionBundle.getSessionBundle)({
    activeOrgIdSelectorName: 'selectActiveOrgId',
    selectorsThatDetermineActivity: ['selectIsActive'],
    retryFailedFetchAfter: 1000
  });
  const sut = bundle.selectActiveOrgType.resultFunc;
  t.equal(sut({
    id: 'cfd',
    roles: ['admin', 'provider'],
    status: null,
    memberId: '06a72fb5-c0c8-4949-89fb-4cf62289a828'
  }), 'regular', 'no type means regular');
  t.equal(sut({
    id: 'cfd',
    roles: ['super'],
    type: 'parent'
  }), 'parent', 'returns parent if relevant');
  t.end();
});
(0, _tape.default)('selectIsXchartUberUser', t => {
  const store = getStore({
    stubs: {
      selectActiveOrgId: () => 'cfd'
    }
  });
  t.equal(store.selectIsXchartUberUser(), false, 'xchart uber user should be false');
  t.equal(store.selectSessionOrgs(), null);
  store.doReceiveSession({
    multiFactorLast: '1628741741839',
    multiFactorAuthExp: '1631333741839',
    sessionRenewedAt: '1628741741839',
    sessionExpiresAt: '1628743541839',
    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InVzZXJfWmRIOHJMY0VCX2hYeWk2aFpaRXNWIiwiZW1haWwiOiJoZW5yaWtAam9yZXRlZy5jb20iLCJzbXMiOiIrMTUwOTUyMTUxMTMiLCJzdXBlciI6dHJ1ZSwib3JncyI6W3siaWQiOiJjZmQiLCJyb2xlcyI6WyJhZG1pbiIsInByb3ZpZGVyIl0sIm1lbWJlcklkIjoiMDZhNzJmYjUtYzBjOC00OTQ5LTg5ZmItNGNmNjIyODlhODI4In0seyJpZCI6ImFzZGZhc2RmYXNkZmFzZmFzZCIsInJvbGVzIjpbImFkbWluIiwicHJvdmlkZXIiXSwibWVtYmVySWQiOiI4ZTVmYjgwMy1hMDYyLTQxOGUtOTk2OS1jNDEzMDc1MjUzOTMifV0sInNlc3Npb24iOjE2Mjg3NDE3NDE4MzksIm1mYSI6MTYyODc0MTc0MTgzOSwidHlwZSI6ImF1dGgiLCJpYXQiOjE2Mjg3NDE4ODl9.Ef2AWOFiKfkhV-eExVgoLP70KtbnKPS6tabT6n7W6jQ',
    orgs: [{
      id: 'xchart',
      roles: ['uber'],
      type: 'xchart'
    }, {
      id: 'asdfasdfasdfasfasd',
      roles: ['admin', 'provider'],
      status: null,
      memberId: '8e5fb803-a062-418e-9969-c41307525393'
    }]
  });
  t.equal(store.selectIsXchartUberUser(), true, 'xchart uber user should be true');
  t.end();
});