import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, EMPTY, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { UPDATE_ROLE_ITEM } from '@/graphql/services/rolesPermissions/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/rolesPermissions/types/payload/roleItem';

import * as selectors from '../selectors';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `mutation ${UPDATE_ROLE_ITEM}($payload: ${PAYLOAD_NAME}) {
  ${UPDATE_ROLE_ITEM}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const displayName = selectors.displayNameSelector(state$.value);
      const accountId = selectors.accountSelector(state$.value)?.id;
      const defaultPage = selectors.defaultPageSelector(state$.value);
      const readOnlyInSelfServe = selectors.readOnlyInSelfServeSelector(state$.value);
      const visibleInSelfServe = selectors.visibleInSelfServeSelector(state$.value);
      const permissionsObject = selectors.permissionsSelector(state$.value);

      const permissions = Object.keys(permissionsObject).filter((permission) => permissionsObject[permission]);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: action.payload,
            displayName,
            defaultPage,
            readOnlyInSelfServe,
            visibleInSelfServe,
            permissions,
            ...(accountId && { accountId }),
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/roles-permissions');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Updated',
              }),
            );
          }

          return EMPTY;
        }),
      );

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