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 { SAVE_RULE_ACTION_REMOVE, SAVE_RULE_ACTION_SAVE } from '@/modules/userRulesSettings/constants';

import { createRequestBodyFromState } from '../../helpers';
import { saveRulesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation SaveUserRules(
    $rules: [UserRulesInputType]
  ) {
    saveUserRules(
      rules: $rules
    ) {
      rules {
        ruleId
        ruleName
      }
    }
  }
`;

// const getResponse = ({ data: { saveUserRules } }) => saveUserRules;

export default (action$, state$) =>
  action$.pipe(
    ofType(saveRulesAction.type),
    switchMap((action) => {
      const rules = createRequestBodyFromState(state$.value);
      const messages = {
        [SAVE_RULE_ACTION_SAVE]: 'Rule saved',
        [SAVE_RULE_ACTION_REMOVE]: 'Rule deleted',
      };
      const message = messages[action.payload];

      const stream$ = gqlRequest({
        query,
        variables: {
          rules,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message,
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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