import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { debounceTime, filter, switchMap } from 'rxjs/operators';

import { getPublishersAction, setPublishersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

import type { RootState } from '@/modules/@common/store/store';

const gqlQuery = `
  query GetPublishDestinationPublishers(
    $watchEnabledOnly: Boolean!,
    $removeDisabled: Boolean!,
    $formEnabledOnly: Boolean,
    $searchText: String,
    $limit: Int
  ) {
    getPublishDestinationPublishers(
      watchEnabledOnly: $watchEnabledOnly,
      removeDisabled: $removeDisabled,
      formEnabledOnly: $formEnabledOnly
      searchText: $searchText
      limit: $limit
    ) {
      id
      name
    }
  }
`;

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getPublishersAction> => action.type === getPublishersAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: gqlQuery,
        variables: {
          watchEnabledOnly: false,
          removeDisabled: true,
          limit: 20,
          searchText: action.payload || '',
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setPublishersAction(data.getPublishDestinationPublishers)));
          }

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

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

export default epic;
