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 * as templateSelector from '../selectors';
import { deleteTemplateAction, getTemplatesAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation DeleteFormTemplate(
    $id: Int
  ) {
    deleteFormTemplate(
      id: $id
    )
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(deleteTemplateAction.type),
    switchMap(({ payload: id }) => {
      const state = state$.value;
      const templates = templateSelector.templatesSelector(state);
      const page = templateSelector.pageSelector(state);

      const stream$ = gqlRequest({
        query,
        variables: { id },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const actions = [];

            if (templates.length === 1) {
              actions.push(
                of(
                  setFieldAction({
                    page: page === 1 ? page : page - 1,
                  }),
                ),
              );
            }

            actions.push(
              of(getTemplatesAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Template deleted',
                }),
              ),
            );

            return concat(...actions);
          }

          return EMPTY;
        }),
      );

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