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

import { GET_XRAY_CAMPAIGN_ITEM } from '@/graphql/services/xRayCampaings/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

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

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

const query = `
  query ${GET_XRAY_CAMPAIGN_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_CAMPAIGN_ITEM}(payload: $payload) {
      name
      advertisingBrand {
        id
        name
      }
      publisher {
        id
        name
      }
    }
  }
`;

const getResponse = ({ data }) => {
  const item = data[GET_XRAY_CAMPAIGN_ITEM];

  return {
    name: item.name,
    advertiser: item.advertisingBrand,
    hub: item.publisher,
  };
};

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id: action.payload.id,
            },
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open for edit",
                }),
              ),
            );

            Router.push('/x-ray/campaigns');
          } else {
            const data = getResponse(response);

            actions.push(
              of(
                setAction({
                  ...data,
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

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