import expect from 'expect';
import fetchMock from 'fetch-mock';

import createTestStore from 'mtest/helpers/createTestStore';
import {
  EVENT_ID,
  EVENT_PAYLOAD,
  NOT_EVENT_ID,
  mockEvent,
  mockEvent404,
  mockPremiereEvent,
} from 'mtest/fetchMocks/event';

import {
  EVENTS_DATA_EVENT_LOADED_ACTION_TYPE,
  EVENTS_DATA_EVENT_FAILED_ACTION_TYPE,
  eventsDataFetchEvent,
  eventsDataLoadEvent,
} from 'mweb/common/actions/data/events';
import { PremiereStatus } from 'mweb/common/reducers/data/events';
import { supportedPremiereEvents } from 'mweb/common/utils/premiereUtils';

describe('eventsData actions', () => {
  afterEach(() => {
    expect(fetchMock.done()).toEqual(true);
    fetchMock.restore();
  });

  describe('eventsDataFetchEvent', () => {
    it('resolves event JSON on success', () => {
      const store = createTestStore();
      mockEvent();

      return store.dispatch(eventsDataFetchEvent(EVENT_ID)).then(() => {
        const actions = store.getActions();
        expect(actions.shift()).toEqual(eventsDataLoadEvent(EVENT_PAYLOAD));
      });
    });

    it('rejects with the response on 404', () => {
      const store = createTestStore();
      mockEvent404();

      return store.dispatch(eventsDataFetchEvent(NOT_EVENT_ID)).then(() => {
        const actions = store.getActions();
        expect(actions.shift().type).toEqual(
          EVENTS_DATA_EVENT_FAILED_ACTION_TYPE,
        );
      });
    });

    Object.keys(PremiereStatus)
      .map(status => (PremiereStatus as any)[status])
      .filter(val => !supportedPremiereEvents.includes(val))
      .forEach(status => {
        it(`dispatches failure on unsupported premiere event status: ${status}`, () => {
          const store = createTestStore();
          mockPremiereEvent(status);
          return store.dispatch(eventsDataFetchEvent(EVENT_ID)).then(() => {
            const actions = store.getActions();
            expect(actions.shift().type).toEqual(
              EVENTS_DATA_EVENT_FAILED_ACTION_TYPE,
            );
          });
        });
      });
  });

  describe('eventsDataLoadEvent', () => {
    it('builds the correct payload from the JSON when game is present', () => {
      expect(eventsDataLoadEvent(EVENT_PAYLOAD)).toEqual({
        type: EVENTS_DATA_EVENT_LOADED_ACTION_TYPE,
        payload: EVENT_PAYLOAD,
      });
    });
  });
});
