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

import { excludeVideoIdsSelector, isSelectedAllSelector, monitoringIdsSelector, videoIdsSelector } from '../selectors';
import { changeAccessLevelAction, closeAction, getMonitoringStateAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import {
  accessLevelSelector,
  hubsSelector,
  sendHubsNotificationSelector,
} from '@/modules/editorial/bulkActions/components/BulkActionShare/redux/selectors';
import { currentFiltersAsStringSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';

const queryGQL = `
  mutation VideoBulkActionChangeAccessLevel(
    $applyToAllVideo: Boolean,
    $videoIds: [String],
    $excludeVideoIds: [String],
    $filters: String,
    $level: String,
    $hubs: [String],
    $sendHubsNotification: Boolean,
  ) {
    videoBulkActionChangeAccessLevel(
      applyToAllVideo: $applyToAllVideo,
      videoIds: $videoIds,
      excludeVideoIds: $excludeVideoIds,
      filters: $filters,
      level: $level,
      hubs: $hubs,
      sendHubsNotification: $sendHubsNotification,
    ) {
      monitoringId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(changeAccessLevelAction.type),
    switchMap(() => {
      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 level = accessLevelSelector(state);
      const hubs = hubsSelector(state);
      const sendHubsNotification = sendHubsNotificationSelector(state);

      const variables = {
        applyToAllVideo,
        videoIds,
        excludeVideoIds,
        filters,
        level,
      };

      if (hubs?.length) {
        variables.hubs = hubs.map((hub) => `${hub.id}`);
        variables.sendHubsNotification = sendHubsNotification;
      }

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

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

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

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