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

import { ROWS_PER_PAGE_DEFAULT } from '../../constants';

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

const query = `
  query getHubsDemandAccountsOptions(
    $searchText: String
    $pageSize: Int
  ) {
    getHubsDemandAccountsOptions(
      searchText: $searchText
      pageSize: $pageSize
    ) {
    records{
      id
      name
      }
      recordsTotal
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getDemandAccountsOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search?.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actions = [];
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload.searchText ?? '',
          pageSize: ROWS_PER_PAGE_DEFAULT,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  demandAccountsOptions: response.data.getHubsDemandAccountsOptions?.records,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(
        of(
          setAction({
            demandAccountsOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
