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

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

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

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

const query = `
  query ${GET_XRAY_CREATIVE_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_CREATIVE_ITEM}(payload: $payload) {
      id
      publisher {
        id
        name
      }
      name
      title
      image
      buttonLabel1
      buttonUrl1
      buttonLabel2
      buttonUrl2
      impressionTracker
      clickTracker1
      clickTracker2
    }
  }
`;

const getResponse = ({ data }) => {
  const { publisher, ...item } = data[GET_XRAY_CREATIVE_ITEM];

  return {
    ...item,
    hub: publisher,
  };
};

const trimUrl = (url) => (typeof url === 'string' ? url.trim() : '');

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const { id, isDuplicate } = action.payload;
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            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/creatives');
          } else {
            const data = getResponse(response);

            actions.push(
              of(
                setAction({
                  ...data,
                  name: isDuplicate ? `Copy of ${data.name}` : data.name,
                  buttonUrl1: trimUrl(data.buttonUrl1),
                  buttonUrl2: trimUrl(data.buttonUrl2),
                  impressionTracker: trimUrl(data.impressionTracker),
                  clickTracker1: trimUrl(data.clickTracker1),
                  clickTracker2: trimUrl(data.clickTracker2),
                }),
              ),
            );
          }

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

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