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, replaceTagsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { currentFiltersAsStringSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';

const queryGQL = `
  mutation VideoBulkActionReplaceTags(
    $applyToAllVideo: Boolean,
    $videoIds: [String],
    $excludeVideoIds: [String],
    $filters: String,
    $find: BulkActionTags
    $replace: BulkActionTags,
  ) {
    videoBulkActionReplaceTags(
      applyToAllVideo: $applyToAllVideo,
      videoIds: $videoIds,
      excludeVideoIds: $excludeVideoIds,
      filters: $filters,
      find: $find,
      replace: $replace,
    ) {
      monitoringId
    }
  }
`;

const getFindReplaceTagsObjectWithReformatedKeys = (findReplaceTagsObject) => ({
  keywords: findReplaceTagsObject.keywords,
  iab: findReplaceTagsObject.iab,
  labels: findReplaceTagsObject.labels,
});

export default (action$, state$) =>
  action$.pipe(
    ofType(replaceTagsAction.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);

      // Action payload has only one tag, others empty array
      // example: { keywords: [], iab: [Object], labels: [] }
      // const findTagObject = Object
      //   .keys(find)
      //   .reduce((acc, tagKey) => (find[tagKey].length ? { [tagKey]: find[tagKey][0] } : acc), {});

      const variables = {
        applyToAllVideo,
        videoIds,
        excludeVideoIds,
        filters,
        find: getFindReplaceTagsObjectWithReformatedKeys(find),
        replace: getFindReplaceTagsObjectWithReformatedKeys(replace),
      };

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

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

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

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