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

import { GET_ROLE_ITEM } from '@/graphql/services/rolesPermissions/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

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

import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query ${GET_ROLE_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_ROLE_ITEM}(payload: $payload) {
      displayName
      type
      account {
        id
        name
      }
      defaultPage
      visibleInSelfServe
      readOnlyInSelfServe
      permissions {
        id
        name
      }
      permissionsModules {
        id
        displayName
        description
        permissions {
          id
          name
          displayName
          description
          disabled
          hidden
          type
        }
      }
    }
  }
`;

const getResponse = ({ data }) => {
  const { publisher, ...item } = data[GET_ROLE_ITEM];

  return {
    ...item,
    hub: publisher,
  };
};

function clearNullableValues(data) {
  return Object.fromEntries(Object.entries(data).filter((entry) => entry[1] !== null));
}

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const { id, isDuplicate } = action.payload;
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id,
            },
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open for edit",
                }),
              ),
            );

            Router.push('/roles-permissions');
          } else {
            const data = clearNullableValues(getResponse(response));

            const payload = {
              ...data,
              displayName: isDuplicate ? `Copy of ${data.displayName}` : data.displayName,
              permissions: {},
            };

            if (data.permissions) {
              payload.permissions = data.permissions.reduce((acc, permission) => {
                acc[permission.name] = true;
                return acc;
              }, {});
            }

            actions.push(of(setAction(payload)));
          }

          return concat(...actions);
        }),
      );

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