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

const queryGQL = `
  mutation VideoBulkActionShareWithUsers(
    $applyToAllVideo: Boolean,
    $videoIds: [String],
    $excludeVideoIds: [String],
    $filters: String,
    $userIds: [String],
    $message: String,
  ) {
    videoBulkActionShareWithUsers(
      applyToAllVideo: $applyToAllVideo,
      videoIds: $videoIds,
      excludeVideoIds: $excludeVideoIds,
      filters: $filters,
      userIds: $userIds,
      message: $message
    ) {
      monitoringId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(shareWithUsersAction.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 users = usersSelector(state);
      const message = messageSelector(state);

      const variables = {
        applyToAllVideo,
        videoIds,
        excludeVideoIds,
        filters,
        userIds: users.map((user) => `${user.id}`),
        message,
      };

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

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

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

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