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

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

const query = `
  query WatchGetDomains(
    $pageSize: Int,
    $searchText: String,
    $publisherId: Int,
  ) {
    watchGetDomains(
      pageSize: $pageSize,
      searchText: $searchText
      publisherId: $publisherId,
    ) {
      records {
        id
        domain
      }
    }
  }
`;

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

export default (action$, state$) =>
  action$.pipe(
    ofType(getDomainOptionsAction.type),
    switchMap((action) => {
      const hub = watchSelectors.hubSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          publisherId: hub.value,
          top: 30,
          searchText: action.payload ?? '',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

      return concat(
        of(
          updateStoreByPropAction({
            domainOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
