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

import { UPDATE_XRAY_CAMPAIGN } from '@/graphql/services/xRayCampaings/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayCampaings/types/payload/xRayCampaignItem';

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

const query = `mutation ${UPDATE_XRAY_CAMPAIGN}($payload: ${PAYLOAD_NAME}) {
  ${UPDATE_XRAY_CAMPAIGN}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const name = selectors.nameSelector(state$.value);
      const advertisingBrandId = selectors.advertiserSelector(state$.value)?.id;
      const publisherId = selectors.hubSelector(state$.value)?.id;

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: action.payload,
            name,
            advertisingBrandId,
            publisherId,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/x-ray/campaigns');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Updated',
              }),
            );
          }

          return EMPTY;
        }),
      );

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