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

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

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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updatePermissionsMetadataAction.type),
    switchMap((action) => {
      const permissionsModules = selectors.permissionsModulesSelector(state$.value);
      const { id, displayName, description, moduleId } = action.payload;

      const payloadForApi = {
        id,
        displayName,
        description,
      };

      const payloadForUiState = permissionsModules.map((module) =>
        module.id === moduleId
          ? {
              ...module,
              permissions: module.permissions.map((perm) =>
                perm.id === payloadForApi.id ? { ...perm, ...payloadForApi } : perm,
              ),
            }
          : module,
      );

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: payloadForApi,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Permission saved successfully',
                }),
              ),
              of(setAction({ permissionsModules: payloadForUiState })),
            );
          }

          return EMPTY;
        }),
      );

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