import { logger } from 'tachyon-logger';
import { Dispatch } from 'redux';

import { fetchVOD, VODDataPayload } from 'mweb/common/fetch/vods';
import { RootState } from 'mweb/common/reducers/root';
import { GQLError } from 'mweb/common/fetch/fetchGQL';

export const VODS_DATA_VOD_LOADED_ACTION_TYPE =
  'VODS_DATA_VOD_LOADED_ACTION_TYPE';
export interface VODsDataVODLoadedAction {
  type: typeof VODS_DATA_VOD_LOADED_ACTION_TYPE;
  payload: VODDataPayload;
}

export const VODS_DATA_VOD_FAILED_ACTION_TYPE =
  'VODS_DATA_VOD_FAILED_ACTION_TYPE';
export interface VODsDataVODFailedAction {
  type: typeof VODS_DATA_VOD_FAILED_ACTION_TYPE;
  payload: GQLError;
}

export type VODsDataAction = VODsDataVODLoadedAction | VODsDataVODFailedAction;

export function vodsDataFetchVOD(
  vodID: string,
): (dispatch: Dispatch<RootState>) => Promise<void> {
  return async dispatch => {
    logger.info(`Attempting to load data for VOD ${vodID}`);
    try {
      const data = await fetchVOD(vodID);
      if (data) {
        dispatch(vodsDataLoadVOD(data));
      } else {
        dispatch(vodsDataFailVOD({ status: 404 }));
      }
    } catch (vodsDataFetchVODError) {
      logger.warn({ vodsDataFetchVODError });
      dispatch(vodsDataFailVOD(vodsDataFetchVODError));
    }
  };
}

export function vodsDataLoadVOD(
  payload: VODDataPayload,
): VODsDataVODLoadedAction {
  return {
    type: VODS_DATA_VOD_LOADED_ACTION_TYPE,
    payload,
  };
}

export function vodsDataFailVOD(error: GQLError): VODsDataVODFailedAction {
  return {
    type: VODS_DATA_VOD_FAILED_ACTION_TYPE,
    payload: error,
  };
}
