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

import { getFeedOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query GetVideoFeedSourcesByAccount(
    $searchText: String,
  ) {
    getVideoFeedSourcesByAccount(
      searchText: $searchText,
    ) {
      records {
        id
        name
        description
        schedule_status
        status
        accessLevel
        contentOwner {
          id
          name
        }
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getFeedOptionsAction.type),
    debounceTime(+process.env.APP_CLEAR_TIMEOUT),
    switchMap(({ payload = '' }) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          searchText: payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length && data.getVideoFeedSourcesByAccount) {
            const feedOptions = data.getVideoFeedSourcesByAccount.records.map((feed) => ({
              label: feed.description.length ? feed.description : `Invalid data(${feed.name})`,
              value: feed.id,
              feedDescription: feed.description,
              feedSource: feed.name,
              scheduleStatus: feed.schedule_status,
              accessLevel: feed.accessLevel,
              contentOwner: {
                label: feed.contentOwner.name,
                value: feed.contentOwner.id,
              },
            }));

            actions.push(of(setAction({ feedOptions })));
          }

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

      return concat(stream$);
    }),
  );
