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

import { GET_USER_ROLE_OPTIONS } from '@/graphql/services/users/constants';
import { ACCOUNT } from '@/modules/@common/user/constants/rolesType';

import { getRoleOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserRoleTypeSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query ${GET_USER_ROLE_OPTIONS} {
    ${GET_USER_ROLE_OPTIONS} {
      id
      name
      type
      displayName
      visibleInSelfServe
      readOnlyInSelfServe
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getRoleOptionsAction.type),
    switchMap(() => {
      const isAccountType = getUserRoleTypeSelector(state$.value) === ACCOUNT;

      const stream$ = gqlRequest({
        query,
        variables: {},
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const roleOptions = response.data[GET_USER_ROLE_OPTIONS].filter(
              (item) => !isAccountType || (!item.readOnlyInSelfServe && item.visibleInSelfServe),
            ).map((role) => ({
              value: role.id,
              label: role.displayName,
              ...role,
            }));

            actions.push(
              of(
                setAction({
                  roleOptions,
                }),
              ),
            );
          }

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

      return concat(
        of(
          setAction({
            roleOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
