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

import { configSelector } from '../../../filterContainer/redux/selectors';
import { hubsListAction, hubsListLoadingAction, hubsSearchPrefixAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getPublishersForVideoFilter(
    $searchText: String,
    $pageSize: Int,
    $accountId: Int
  ) {
    getPublishersForVideoFilter(
      searchText: $searchText,
      pageSize: $pageSize,
      accountId: $accountId, 
    ) {
      id
      name
    }
  }
`;

const getResponse = ({ data: { getPublishersForVideoFilter } }) =>
  getPublishersForVideoFilter.map((entity) => ({
    value: entity.id,
    label: entity.name,
  }));

export default (action$, state$) =>
  action$.pipe(
    ofType(hubsSearchPrefixAction.type),
    switchMap((action) => {
      const state = state$.value;

      const config = configSelector(state);
      const accountId = config.account.filters?.[0].value[0]?.value;

      const variables = {
        searchText: action.payload?.prefix ?? '',
        pageSize: 30,
      };

      if (accountId) {
        variables.accountId = accountId;
      }

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

          if (!response.errors.length) {
            const accountOptions = getResponse(response);

            actions.push(of(hubsListAction(accountOptions)));
          }

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

      return concat(of(hubsListLoadingAction(true)), stream$, of(hubsListLoadingAction(false)));
    }),
  );
