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 { TYPE_BUSINESS, TYPE_PUBLISHER, TYPE_VAST } from '@/modules/@common/constants/account';
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
      displayName
      visibleInSelfServe
      readOnlyInSelfServe
    }
  }
`;

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

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText,
            pageSize: 30,
            filtersValues: [TYPE_PUBLISHER, TYPE_BUSINESS, TYPE_VAST],
          },
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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

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