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

import { getSitesListAction, setSitesListAction, sitesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { persistHubs } from '@/modules/uploaderNew/helpers/persist';

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

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

export default (action$) =>
  action$.pipe(
    ofType(getSitesListAction.type),
    switchMap(() => {
      const variables = {
        pageSize: 10000,
      };

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

          if (!response.errors.length) {
            const savedHubs = persistHubs.get() || [];
            const hubs = getResponse(response);
            const savedInHubs = savedHubs.filter((sh) => hubs?.find((h) => h.value === sh.value));

            if (savedInHubs.length) {
              actions.push(of(sitesAction(savedInHubs)));
            }

            actions.push(of(setSitesListAction(hubs)));
          }

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

      return concat(of(setSitesListAction(null)), stream$);
    }),
  );
