import { logger } from 'tachyon-logger';
import { Dispatch } from 'redux';
import { fetchEvent, EventDataPayload } from 'mweb/common/fetch/events';
import { RootState } from 'mweb/common/reducers/root';
import { GQLError } from 'mweb/common/fetch/fetchGQL';
import { isUnsupportedPremiereEvent } from 'mweb/common/utils/premiereUtils';

export const EVENTS_DATA_EVENT_LOADED_ACTION_TYPE =
  'EVENTS_DATA_EVENT_LOADED_ACTION_TYPE';
export interface EventsDataEventLoadedAction {
  type: typeof EVENTS_DATA_EVENT_LOADED_ACTION_TYPE;
  payload: EventDataPayload;
}

export const EVENTS_DATA_EVENT_FAILED_ACTION_TYPE =
  'EVENTS_DATA_EVENT_FAILED_ACTION_TYPE';
export interface EventsDataEventFailedAction {
  type: typeof EVENTS_DATA_EVENT_FAILED_ACTION_TYPE;
  payload: GQLError;
}

export type EventsDataAction =
  | EventsDataEventLoadedAction
  | EventsDataEventFailedAction;

export function eventsDataFetchEvent(
  eventID: string,
): (dispatch: Dispatch<RootState>) => Promise<void> {
  return async dispatch => {
    logger.info(`Attempting to load event data for ${eventID}`);
    try {
      const response = await fetchEvent(eventID);
      if (!response || isUnsupportedPremiereEvent(response.event)) {
        dispatch(eventsDataFailEvent({ status: 404 }));
      } else {
        dispatch(eventsDataLoadEvent(response));
      }
    } catch (eventsDataFetchEventError) {
      logger.warn({ eventsDataFetchEventError });
      dispatch(eventsDataFailEvent(eventsDataFetchEventError));
    }
  };
}

export function eventsDataLoadEvent(
  payload: EventDataPayload,
): EventsDataEventLoadedAction {
  return {
    type: EVENTS_DATA_EVENT_LOADED_ACTION_TYPE,
    payload,
  };
}

export function eventsDataFailEvent(
  error: GQLError,
): EventsDataEventFailedAction {
  return {
    type: EVENTS_DATA_EVENT_FAILED_ACTION_TYPE,
    payload: error,
  };
}
