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

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

import { createTemplateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import createRequestBody from '@/modules/forms/templateEditor/helpers/createRequestBody';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation CreateFormTemplate(
    $template: FormTemplateInputType
  ) {
    createFormTemplate(
      template: $template
    ) {
       id
       name
    }
  }
`;

const getResponse = ({ data: { createFormTemplate } }) => createFormTemplate;

export default (action$, state$) =>
  action$.pipe(
    ofType(createTemplateAction.type),
    switchMap(() => {
      const state = state$.value;
      const template = createRequestBody(state);

      const stream$ = gqlRequest({
        query,
        variables: {
          template,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);
            const link = `/form-templates/${data.id}`;

            Router.push(link);

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

          return EMPTY;
        }),
      );

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