import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';
import {inject as injectService} from '@ember/service';
import RSVP from 'rsvp';

// used by ember-simple-auth to store login session data
export default AdaptiveStore.extend({
    localStorageKey: 'fw:session',
    cookieName: 'fw:session',

    currentUser: injectService(),

    /**
     * We override this method in order to log in the user regardless of whether or not
     * the frontend thinks they are. As long as they are logged in on the backend,
     * this will force a user login
     */
    restore() {
        return this._super().then(({authenticated}) => {
            if (authenticated && authenticated.authenticator) {
                return RSVP.resolve({authenticated});
            }

            return this.get('currentUser').check();
        }).then((isActive) => {
            if (!isActive) {
                return RSVP.resolve({authenticated: {}});
            }

            return RSVP.resolve({authenticated: {authenticator: 'authenticator:group-control'}});
        });
    }
});