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

import { CREATE_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 { accountSelector, nameSelector } from '../selectors';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

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

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

          return EMPTY;
        }),
      );

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