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

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

const query = `
  query getEntitiesAccountsOptions(
    $searchText: String,
  ) {
    getEntitiesAccountsOptions(
      searchText: $searchText,
    ) {
      id
      name
    }
  }
`;

const getResponse = ({ data: { getEntitiesAccountsOptions } }) =>
  getEntitiesAccountsOptions.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: {
          searchText: action.payload ?? '',
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                accountOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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