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

import { SORT_ASC } from '@/modules/@common/constants/sort';

import { getUsersOptionsAction, setModuleStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getUsersForUserRules(
    $searchText: String,
    $searchIn: [String],
    $page: Int,
    $pageSize: Int,
    $sortOrder: String,
    $sortBy: String,
  ) {
    getUsersForUserRules(
      searchText: $searchText,
      searchIn: $searchIn,
      page: $page,
      pageSize: $pageSize,
      sortOrder: $sortOrder, 
      sortBy: $sortBy,
    ) {
      id
      email
      firstName
      lastName
    }
  }
`;

const getResponse = ({ data: { getUsersForUserRules } }) => getUsersForUserRules;

export default (action$) =>
  action$.pipe(
    ofType(getUsersOptionsAction.type),
    switchMap((action) => {
      const variables = {
        pageSize: 30,
        searchText: action.payload,
        searchIn: ['firstName', 'lastName', 'email'],
        sortBy: 'firstName',
        sortOrder: SORT_ASC,
      };

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

          if (!response.errors.length) {
            actions.push(
              of(
                setModuleStateAction({
                  usersOptions: getResponse(response),
                }),
              ),
            );
          }

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

      return concat(
        of(
          setModuleStateAction({
            usersOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
