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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import createDemandTagRequestBody from '../../helpers/createDemandTagRequestBody';
import * as selectors from '../selectors';
import { duplicateDemandTagAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation DuplicateDemandTag(
    $tag: MarketplaceDemandTagInputType
  ) {
    duplicateDemandTag(
      tag: $tag
    ) {
       id
       name
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(duplicateDemandTagAction.type),
    switchMap(() => {
      const state = state$.value;
      const tag = createDemandTagRequestBody(state);
      const pageConfig = selectors.pageConfigSelector(state);

      const stream$ = gqlRequest({
        query,
        variables: {
          tag,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            let link = `/demand/${pageConfig.demandAccount.id}/advertisers/${pageConfig.advertiser.id}/tags/${data.duplicateDemandTag.id}`;

            link += `?accountName=${encodeURIComponent(pageConfig.demandAccount.name)}&advertiserName=${encodeURIComponent(pageConfig.advertiser.name)}&tagName=${encodeURIComponent(data.duplicateDemandTag.name)}`;

            Router.push(link);

            actions = [
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Demand tag created',
                }),
              ),
            ];
          }

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

      return concat(of(setFieldAction({ isLoading: true })), stream$, of(setFieldAction({ isLoading: false })));
    }),
  );
