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

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

import * as selectors from '../selectors';
import { getTargetingStatusesAction, removeTargetingAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation RemoveVideoTargeting(
    $videoId: String
    $site: [String]
    $id: String,
  ) {
    removeVideoTargeting(
      videoId:$videoId
      site: $site
      id: $id
    )
  }  
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(removeTargetingAction.type),
    switchMap((action) => {
      const data = selectors.data(state$.value);
      const { videoId, site, id } = action.payload;

      const stream$ = gqlRequest({
        query,
        variables: {
          videoId,
          site,
          id,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const dataForUpdate = data.filter((oldRow) => oldRow.id !== id);

            return concat(
              of(setStateAction({ data: dataForUpdate })),
              of(
                getTargetingStatusesAction({
                  videoId,
                  site,
                }),
              ),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Targeting deleted',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

      return concat(of(setStateAction({ isLoading: true })), stream$, of(setStateAction({ isLoading: false })));
    }),
  );
