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

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

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

import { createAdvertiserAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$) =>
  action$.pipe(
    ofType(createAdvertiserAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            name: action.payload,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(setAction({ advertiser: response.data[CREATE_XRAY_CAMPAIGN_ADVERTISER_BRAND] })),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Created',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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