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 { getFormByIdAction, updateFormAction } 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 UpdateForm(
    $form: FormInputType
  ) {
    updateForm(
      form: $form
    ) {
       id
       name
    }
  }
`;

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updateFormAction.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 concat(
              of(getFormByIdAction({ id: data.id })),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Form updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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