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

import { SORT_ASC } from '@/modules/@common/constants/sort';

import { getAdServerListsAction, setSettingsTabAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getAdServers($searchText: String, $searchIn: [String], $page: Int, $pageSize: Int, $sortOrder: String, , $sortBy: String) {
    getAdServers(searchText: $searchText, searchIn: $searchIn, page: $page, pageSize: $pageSize, sortOrder: $sortOrder, sortBy: $sortBy) {
      records {
        id
        name
        url
        macro
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getAdServerListsAction.type),
    debounce((action) => timer(action.payload?.searchText?.length ? 1000 : 0)),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload?.searchText ?? '',
          searchIn: ['name'],
          page: 1,
          pageSize: 30,
          sortBy: 'name',
          sortOrder: SORT_ASC,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(
                setSettingsTabAction({
                  adServersList: data.getAdServers.records,
                }),
              ),
            ];
          }

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

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