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

import { GET_USER_ACCOUNTS_OPTIONS } from '@/graphql/services/users/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/accounts';

import { getAccountOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_USER_ACCOUNTS_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_USER_ACCOUNTS_OPTIONS}(payload: $payload) {
      id
      name
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_USER_ACCOUNTS_OPTIONS].map((account) => ({
    value: account.id,
    label: account.name,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getAccountOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText: action.payload ?? '',
            pageSize: 30,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                accountOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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