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 { duplicateTemplateAction } 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 DuplicateFormTemplate(
    $template: FormTemplateInputType
  ) {
    duplicateFormTemplate(
      template: $template
    ) {
       id
       name
    }
  }
`;

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

export default (action$, state$) =>
  action$.pipe(
    ofType(duplicateTemplateAction.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 duplicated',
              }),
            );
          }

          return EMPTY;
        }),
      );

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