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 { createFormAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { createRequestBody } from '@/modules/forms/editor/helpers/createRequestBody';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation CreateForm(
    $form: FormInputType
  ) {
    createForm(
      form: $form
    ) {
       id
       name
    }
  }
`;

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

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

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

            Router.push(link);

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

          return EMPTY;
        }),
      );

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