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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(addAccessSitesAction.type),
    switchMap((action) => {
      const sites = action.payload;
      const videoId = selectors.videoIdSelector(state$.value);
      const sendHubsNotification = selectors.sendHubsNotificationSelector(state$.value);

      const dataToSend = {
        videoId,
        sites,
        sendHubsNotification,
      };

      if (sites) {
        dataToSend.sites = sites.map((site) => site.id);
      }

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

          if (!errors.length) {
            actions.push(
              of(setFormCloseAction(false)),
              of(reloadSelectedVideoAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Saved',
                }),
              ),
            );
          }

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

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