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

import { FEED_TYPES, TYPE_LIVE, TYPE_SITEMAP, TYPE_STORY_API } from '@/modules/@common/constants';

import { getSourcesOptionAction, setModuleStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetUserRulesFeedSources(
    $feedTypeFilter: [String],
    $pageSize: Int,
    $searchText: String,
    ) {
      getUserRulesFeedSources(
        feedTypeFilter: $feedTypeFilter,
        pageSize: $pageSize,
        searchText: $searchText
      ) {
        id
        name
        display_name
      }
  }
`;

const getResponse = ({ data: { getUserRulesFeedSources } }) =>
  getUserRulesFeedSources.map((record) => ({
    label: record.display_name || record.name,
    value: record.id,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getSourcesOptionAction.type),
    switchMap((action) => {
      const variables = {
        feedTypeFilter: FEED_TYPES.filter((type) => ![TYPE_STORY_API, TYPE_SITEMAP, TYPE_LIVE].includes(type)),
        searchText: action.payload,
        pageSize: 30,
      };

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

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

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

      return concat(
        of(
          setModuleStateAction({
            sourcesOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
