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

import * as selectors from '../selectors';
import { getWatchOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query AnalyticsWatchesQuery(
    $page: Int,
    $pageSize: Int,
    $publisherIds: [Int],
    $search: String,
    $sortBy: String,
    $sortOrder: String
  ) {
    analyticsWatches(
      page: $page,
      pageSize: $pageSize,
      publisherIds: $publisherIds,
      search: $search,
      sortBy: $sortBy,
      sortOrder: $sortOrder
    ) {
      records {
        id
        title
        watchChannels {
          id
          title
        }
      }
    }
  }
`;

const toOptions = (entity, extra = {}) => ({
  value: entity.id,
  label: entity.title,
  ...extra,
});
const getResponse = ({
  data: {
    analyticsWatches: { records },
  },
}) =>
  records.map((watch) =>
    toOptions(watch, {
      channels: watch.watchChannels.map((channel) => toOptions(channel)),
    }),
  );

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

      const hub = selectors.hubSelector(state);

      const stream$ = gqlRequest({
        query,
        variables: {
          page: 1,
          pageSize: 30,
          publisherIds: [hub.value],
          search: action.payload ?? '',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  watchOptions: getResponse(response),
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            watchOptions: null,
            watchChannelOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
