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

import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

import * as selectors from '../selectors';
import { getFilterByPlayerOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query marketplacePlayers(
    $searchText: String,
    $publisherId: Int
  ) {
    marketplacePlayers(
      searchText: $searchText,
      publisherId: $publisherId
    ) {
      id
      name
      alias
    }
  }
`;

const querySelfServe = `
  query marketplacePlayersSelfServe(
    $searchText: String,
    $publisherId: Int
  ) {
    marketplacePlayersSelfServe(
      searchText: $searchText,
      publisherId: $publisherId
    ) {
      id
      name
      alias
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getFilterByPlayerOptionsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      const state = state$.value;
      const pageConfig = selectors.pageConfigSelector(state);

      const userPermissions = getUserPermissionsSelector(state$.value);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      let requestParams = {};

      if (action.payload?.searchText) {
        requestParams = {
          searchText: action.payload.searchText,
        };
      }

      const stream$ = gqlRequest({
        query: isAdminMP ? query : querySelfServe,
        variables: {
          publisherId: +pageConfig.id,
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                setFieldAction({
                  filterByPlayerOptions:
                    data.marketplacePlayers?.map((item) => ({ label: item.alias, value: item.name })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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