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

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

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

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

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

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

      const payloadForApi = {
        id,
        displayName,
        description,
        permissions: crudPermissions.filter(Boolean).map(({ id: id$, displayName: displayName$, type }) => ({
          id: id$,
          displayName: displayName$,
          description: action.payload[`${type.toLowerCase()}Description`],
        })),
      };

      const payloadForUiState = permissionsModules.map((module) =>
        module.id === id
          ? {
              ...module,
              displayName,
              description,
              permissions: module.permissions.map((perm) => {
                const updatedPerm = payloadForApi.permissions.find((perm$) => perm$.id === perm.id);
                return updatedPerm ? { ...perm, ...updatedPerm } : perm;
              }),
            }
          : module,
      );

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

          return EMPTY;
        }),
      );

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