import Test from 'ember-test';
import { test } from 'qunit';
import { Response } from 'ember-cli-mirage';
import moduleForAcceptance from 'web-client/tests/helpers/module-for-acceptance';

import subscriptionDashScenario from 'web-client/mirage/scenarios/subscription-dash';
import SubscriptionDashPage from 'web-client/tests/pages/dashboards/subscription-dash';
import { stubLogin } from 'web-client/tests/helpers/stub-login';

const USERNAME = 'twitch';
let exceptionHandler;

moduleForAcceptance('Acceptance | dashboard/subscription', {
  beforeEach() {
    this.overrideDefaultMirageResponse = ({ status }) => {
      this.server.get(`http://api.twitch.tv/api/ticket_products/:channel`, () => new Response(status, {}, {}));
    };

    this.page = SubscriptionDashPage.create({ username: USERNAME });

    subscriptionDashScenario(this.server, { name: USERNAME });
    stubLogin({ login: USERNAME });

    exceptionHandler = Test.adapter.exception;
  },

  afterEach() {
    Test.adapter.exception = exceptionHandler;
  }
});

test('visits Dashboard Subscription page', function (assert) {
  assert.expect(2);

  visit(this.page.url());

  andThen(() => {
    assert.equal(currentURL(), '/twitch/dashboard/subscription/', 'URL is correct');
    assert.ok(find(this.page.subscriptionDash()).length > 0, 'at least one <div class="subscription-dash"> is present');
  });
});

test('shows 403 error', function (assert) {
  assert.expect(3);

  // Intentionally testing rejected promise:
  this.overrideDefaultMirageResponse({ status: 403 });
  Test.adapter.exception = () => {};

  visit(this.page.url());

  andThen(() => {
    assert.equal(currentURL(), '/twitch/dashboard/subscription/', 'URL is correct');
    assert.equal(find(this.page.subscriptionDash()).length, 0, 'no <div class="subscription-dash"> is present');

    assert.equal(
      find(this.page.newDashboardParagraphEmptyGrid()).text(),
      'You are not an editor of this channel',
      'has 403 (forbidden) error message'
    );
  });
});

test('shows default error', function (assert) {
  assert.expect(3);

  // Intentionally testing rejected promise:
  this.overrideDefaultMirageResponse({ status: 500 });
  Test.adapter.exception = () => {};

  visit(this.page.url());

  andThen(() => {
    assert.equal(currentURL(), '/twitch/dashboard/subscription/', 'URL is correct');
    assert.equal(find(this.page.subscriptionDash()).length, 0, 'no <div class="subscription-dash"> is present');

    assert.equal(
      find(this.page.newDashboardParagraphEmptyGrid()).text(),
      'Oops, something went wrong',
      'has default error message'
    );
  });
});
