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

import { getPlayersWithDisabledTargeting, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetVideoTargetingPlayersWithDisabledTargeting {
    getVideoTargetingPlayersWithDisabledTargeting {
      records {
        id
        alias
        name
      }
    }
  }
`;

const getResponse = ({ data: { getVideoTargetingPlayersWithDisabledTargeting } }) =>
  getVideoTargetingPlayersWithDisabledTargeting;

export default (action$) =>
  action$.pipe(
    ofType(getPlayersWithDisabledTargeting.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const res = getResponse(response);

            return concat(
              of(
                setStateAction({
                  playersWithDisabledTargeting: res.records,
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

      return concat(of(setStateAction({ isLoading: true })), stream$, of(setStateAction({ isLoading: false })));
    }),
  );
