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 createSupplyTagRequestBody from '../../helpers/createSupplyTagRequestBody';
import * as selectors from '../selectors';
import { createSupplyTagAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation CreateSupplyTag(
    $tag: MarketplaceSupplyTagInputType
  ) {
    createSupplyTag(
      tag: $tag
    ) {
       id
       name
    }
  }
`;

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

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

          if (!errors.length) {
            let link = `/supply/${pageConfig.supplyAccount.id}/sites/${pageConfig.site.id}/tags/${data.createSupplyTag.id}`;

            link += `?accountName=${encodeURIComponent(pageConfig.supplyAccount.name)}&siteName=${encodeURIComponent(pageConfig.site.name)}&tagName=${encodeURIComponent(data.createSupplyTag.name)}`;

            Router.push(link);

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

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

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