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 { deleteAccessSitesAction, setFormCloseAction, setIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

      const dataToSend = {
        videoId,
        sites,
      };

      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)));
    }),
  );
