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

import { ROWS_PER_PAGE_DEFAULT_FILTER } from '@/modules/players/Players/constants';

import { getPublishersOptionsAction, setAction, setPlayerIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getPlayerPublishersOptions(
    $pageSize: Int
    $searchText: String
    $playerType: Int
  ) {
    getPlayerPublishersOptions(
      pageSize: $pageSize
      searchText: $searchText
      playerType: $playerType
    ) {
      records {
        id
        name
        slug
        IntelligentPlayerTemplate{
          id
          slug
          publisher {
            id
            slug
          }
        }
        StoriesPlayerTemplate{
          id
          slug
          publisher {
            id
            slug
          }
        }
        IntelligentAMPPlayerTemplate{
          id
          slug
          publisher {
            id
            slug
          }
        }
        StoriesAMPPlayerTemplate{
          id
          slug
          publisher {
            id
            slug
          }
        }
        VerticalPlayerTemplate{
          id
          slug
          publisher {
            id
            slug
          }
        }
        includePublicContent
        monetization
        publisherDomains {
        id
        domain
        }
        publisherContentOwners {
        id
        contentOwnerId
       }
       }
      recordsTotal
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPublishersOptionsAction.type),
    debounce((action) => {
      const search = action.payload.searchText;
      return timer(search?.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actions = [];
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload.searchText ?? '',
          pageSize: ROWS_PER_PAGE_DEFAULT_FILTER,
          playerType: action.payload.playerType,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  publishersOptions: response.data.getPlayerPublishersOptions.records,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
