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

import { UPDATE_ADVERTISER } from '../../../../../graphql/services/advertisers/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '../../../../../graphql/services/advertisers/types/payload/item';

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const name = nameSelector(state$.value);

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

            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Advertiser updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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