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

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

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$) =>
  action$.pipe(
    ofType(getHubOptionsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        // variables: {
        //   watchEnabledOnly: false,
        //   removeDisabled: true,
        //   removeLimit: true,
        //   formEnabledOnly: false,
        // },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  hubOptions: getResponse(response),
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            hubOptions: null,
            watchOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
