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

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

const query = `
  query getPublisherDomains(
      $publisherId: Int,
  ) {
    getPublisherDomains(
      publisherId: $publisherId,
    ) {
      records {
        id
        domain
      }
    }
  }
`;

const getResponse = ({
  data: {
    getPublisherDomains: { records },
  },
}) => records.map(({ domain }) => ({ value: domain, label: domain }));

export default (action$, state$) =>
  action$.pipe(
    ofType(getDomainOptionsAction.type),
    debounce((action) => timer(action.payload?.length ? 1000 : 0)),
    switchMap(() => {
      const state = state$.value;
      const site = selectors.siteSelector(state);
      const autocomplete = selectors.autocompleteSelector(state);

      const stream$ = gqlRequest({
        query,
        variables: {
          publisherId: +site.value,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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