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

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

import { getHubsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getPublisherIdsSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query AnalyticsPublishers(
    $watchEnabledOnly: Boolean,
    $removeDisabled: Boolean,
    $removeLimit: Boolean,
    $formEnabledOnly: Boolean
  ) {
    analyticsPublishers(
      watchEnabledOnly: $watchEnabledOnly,
      removeDisabled: $removeDisabled,
      removeLimit: $removeLimit,
      formEnabledOnly: $formEnabledOnly
    ) {
      records {
        id
        name
      }
    }
  }
`;

const getResponse = ({ data: { analyticsPublishers } }) =>
  analyticsPublishers?.records?.map((publisher) => ({ value: publisher.id, label: publisher.name })) ?? [];

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

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

          if (!response.errors.length) {
            const hubs = getResponse(response);
            actions.push(
              of(
                setFieldAction({
                  [`${HUB_FILTER_NAME}_FILTER_OPTIONS`]: hubs.filter((hub) => userPublisherIds?.includes(hub.value)),
                }),
              ),
            );
          }

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

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