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

import { getPublishersByIdsAction, setIsSitesLoadingAction, setPublishersByIdsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getPublisherIdsSelector } from '@/modules/@common/user/redux/selectors';

const queryGQL = `
  query getVideoUserHubs (
    $pageSize: Int,
    $searchText: String
  ) {
    getVideoUserHubs (
      pageSize: $pageSize,
      searchText: $searchText,
    ) {
      records {
        id
        name
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPublishersByIdsAction.type),
    filter(() => getPublisherIdsSelector(state$.value).length),
    switchMap((action) => {
      const queryParams = {
        pageSize: 30,
        searchText: action.payload?.searchText ?? '',
      };

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

          if (!errors.length) {
            actions.push(
              of(
                setPublishersByIdsAction(
                  data.getVideoUserHubs.records.map((pub) => ({
                    ...pub,
                    id: `${pub.id}`,
                  })),
                ),
              ),
            );
          }

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

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