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

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

const queryGQL = `
  mutation VideoBulkActionAddTag(
    $applyToAllVideo: Boolean,
    $videoIds: [String],
    $excludeVideoIds: [String],
    $filters: String,
    $keywords: [BulkActionTagKeywordType],
    $iab: [BulkActionTagIabType],
    $labels: [BulkActionTagLabelType],
  ) {
    videoBulkActionAddTag(
      applyToAllVideo: $applyToAllVideo,
      videoIds: $videoIds,
      excludeVideoIds: $excludeVideoIds,
      filters: $filters,
      keywords: $keywords,
      iab: $iab,
      labels: $labels,
    ) {
      monitoringId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(addTagsAction.type),
    switchMap((action) => {
      const { keywords, iab, labels } = 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,
        keywords,
        iab,
        labels,
      };

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

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

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

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