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

import { getSiteOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const getResponse = ({ data: { getFormHubs } }) =>
  getFormHubs.map((publisher) => ({ value: publisher.id, label: publisher.name }));

const query = `
  query GetFormHubs(
    $pageSize: Int
    $searchText: String
  ) {
    getFormHubs(
      searchText: $searchText
      pageSize: $pageSize
    ) {
      id
      name
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getSiteOptionsAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload ?? '',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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