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

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

const query = `
  query WatchGetSources(
    $pageSize: Int,
    $searchText: String,
    $publisherId: Int,
  ) {
    watchGetSources(
      pageSize: $pageSize,
      searchText: $searchText,
      publisherId: $publisherId,
    ) {
      records {
        id
        name
      }
    }
  }
`;

const getResponse = ({
  data: {
    watchGetSources: { records },
  },
}) => records.map((sources) => ({ value: sources.id, label: sources.name }));

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

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

          if (!response.errors.length) {
            actions.push(
              of(
                updateStoreByPropAction({
                  sourceOptions: [].concat(shouldAddAllOptions ? getSourceDefaultValue() : [], getResponse(response)),
                }),
              ),
            );
          }

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

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