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

import { CREATE_XRAY_CREATIVE } from '@/graphql/services/xRayCreatives/constants';
import { TYPE_ERROR, TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayCreatives/types/payload/xRayCreativeItem';

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap((action) => {
      const name = selectors.nameSelector(state$.value);
      const publisherId = selectors.hubSelector(state$.value).id;
      const title = selectors.titleSelector(state$.value);
      const image = selectors.imageSelector(state$.value);
      const buttonLabel1 = selectors.buttonLabel1Selector(state$.value);
      const buttonUrl1 = selectors.buttonUrl1Selector(state$.value);
      const buttonLabel2 = selectors.buttonLabel2Selector(state$.value);
      const buttonUrl2 = selectors.buttonUrl2Selector(state$.value);
      const impressionTracker = selectors.impressionTrackerSelector(state$.value);
      const clickTracker1 = selectors.clickTracker1Selector(state$.value);
      const clickTracker2 = selectors.clickTracker2Selector(state$.value);

      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              name,
              publisherId,
              title,
              image,
              buttonLabel1,
              buttonUrl1,
              buttonLabel2,
              buttonUrl2,
              impressionTracker,
              clickTracker1,
              clickTracker2,
              ...(action.payload ? { copyId: action.payload } : {}),
            },
          },
        },
        { showNotificationMessage: false },
      ).pipe(
        switchMap((response) => {
          const error = response.errors?.[0];
          if (!error) {
            Router.push('/x-ray/creatives');

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

          const message =
            error?.response?.status === 409
              ? `An X-Ray Creative with name ${name} already exists`
              : "Can't create X-Ray Line";

          return of(
            showNotificationAction({
              type: TYPE_ERROR,
              message,
            }),
          );
        }),
      );

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