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

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

import { getUserDomainsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query analyticsUserDomains(
    $searchText: String
  ) {
    analyticsUserDomains(
      searchText: $searchText
    ) {
      id
      domain
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getUserDomainsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      let requestParams = {};

      if (action.payload?.length) {
        requestParams = {
          searchText: action.payload,
        };
      }

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

          if (!errors.length) {
            actions.push(
              of(
                setFieldAction({
                  [`${PLAYER_DOMAIN_FILTER_NAME}_FILTER_OPTIONS`]:
                    data.analyticsUserDomains?.map((item) => ({ label: item.domain, value: item.id })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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