import Route from 'ember-route';
import injectService from 'ember-service/inject';
import $ from 'jquery';

export default Route.extend({
  session: injectService(),
  login: injectService(),
  api: injectService(),

  beforeModel(transition) {
    this._super(...arguments);

    let rootURL = this.get('router.rootURL');
    let login = this.get('session').userData.login;
    let params = { check_2fa: true };

    return this.get('session').validateAuth(params).catch((jqXHR) => {
      let status = jqXHR.status;
      let path = `/${login}/dashboard/subscription/payouts`;
      let model = { status, path };
      let userModel = this.modelFor('user');

      this.intermediateTransitionTo('dashboards.subscription-dash.payout-settings.error', userModel, model);
      transition.abort();

      if (status === 401) {
        let options = { redirect_on_login: `${rootURL}${login}/dashboard/subscription/payouts` };

        $.login({ options });
      }
    });
  },

  model(params, transition) {
    let login = this.get('session').userData.login;

    return this.get('api').request('get', '/api/payouts/get_tipalti_url').catch((jqXHR) => {
      let status = jqXHR.status;
      let path = `/${login}/dashboard/subscription/payouts`;
      let model = { status, path };
      let userModel = this.modelFor('user');

      this.intermediateTransitionTo('dashboards.subscription-dash.payout-settings.error', userModel, model);
      transition.abort();
    });
  }
});
