import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';

import { excludeVideoIdsSelector, isSelectedAllSelector, monitoringIdsSelector, videoIdsSelector } from '../selectors';
import { closeAction, getMonitoringStateAction, replaceHubsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { currentFiltersAsStringSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';

const queryGQL = `
  mutation VideoBulkActionReplaceHubs(
    $applyToAllVideo: Boolean,
    $videoIds: [String],
    $excludeVideoIds: [String],
    $filters: String,
    $findSites: [String]
    $replaceSites: [String],
  ) {
    videoBulkActionReplaceHubs(
      applyToAllVideo: $applyToAllVideo,
      videoIds: $videoIds,
      excludeVideoIds: $excludeVideoIds,
      filters: $filters,
      findSites: $findSites,
      replaceSites: $replaceSites,
    ) {
      monitoringId
    }
  }
`;

const siteMap = (site) => `${site.value}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(replaceHubsAction.type),
    switchMap((action) => {
      const { find, replace } = action.payload;
      const state = state$.value;

      const applyToAllVideo = isSelectedAllSelector(state);
      const videoIds = videoIdsSelector(state);
      const excludeVideoIds = excludeVideoIdsSelector(state);
      const filters = currentFiltersAsStringSelector(state);
      const monitoringIds = monitoringIdsSelector(state);

      const variables = {
        applyToAllVideo,
        videoIds,
        excludeVideoIds,
        filters,
        findSites: find.map(siteMap),
      };

      if (replace?.length) {
        variables.replaceSites = replace.map(siteMap);
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables,
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const response = data.videoBulkActionReplaceHubs;

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  monitoringIds: [...monitoringIds, response.monitoringId],
                }),
              ),
              of(getMonitoringStateAction()).pipe(delay(500)),
              of(closeAction()),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(stream$);
    }),
  );
