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

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

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

const toOptions = (entity, extra = {}) => ({
  value: entity.id,
  label: entity.title,
  ...extra,
});
const getResponse = ({
  data: {
    getFormWatches: { 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)),
    filter(() => selectors.siteSelector(state$.value)),
    switchMap((action) => {
      const state = state$.value;
      const site = selectors.siteSelector(state);
      const autocomplete = selectors.autocompleteSelector(state);

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

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

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

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