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 { STATUS_ARCHIVE } from '@/modules/forms/forms/constants';

import { getFormsAction, toArchiveAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$) =>
  action$.pipe(
    ofType(toArchiveAction.type),
    switchMap(({ payload: id }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          form: {
            id,
            status: STATUS_ARCHIVE,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(getFormsAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Form archived',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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