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

import { ACCESS_LEVEL_CO_PUBLIC, SITE } from '../../constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { reloadSelectedVideoAction } from '../../../editorialVideoDetails/redux/slices';
import * as selectors from '../selectors';
import { changeAccessLevelAction, setFormCloseAction, setIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  mutation accessChangeLevel(
    $level: String,
    $videoId: String,
    $sites: [String],
    $sendHubsNotification: Boolean,
  ) {
    accessChangeLevel(
      level: $level,
      videoId: $videoId,
      sites: $sites,
      sendHubsNotification: $sendHubsNotification,
    ) {
      data
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(changeAccessLevelAction.type),
    switchMap((action) => {
      const { level, sites } = action.payload;

      const videoId = selectors.videoIdSelector(state$.value);
      const sendHubsNotification = selectors.sendHubsNotificationSelector(state$.value);

      const dataToSend = {
        videoId,
        level,
      };

      dataToSend.sendHubsNotification = level === SITE ? sendHubsNotification : false;

      if (sites) {
        dataToSend.sites = sites;
      }

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

          if (!errors.length) {
            const accessLevelLabel = ACCESS_LEVEL_CO_PUBLIC.find(
              (accessLevel) => accessLevel.value === level,
            )?.label.toLowerCase();

            actions.push(
              of(setFormCloseAction(false)),
              of(reloadSelectedVideoAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: `Video has been changed to ${accessLevelLabel}`,
                }),
              ),
            );
          }

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

      return concat(of(setIsLoadingAction(true)), stream$, of(setIsLoadingAction(false)));
    }),
  );
