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

import { getPlatformsAction, setSettingsTabAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query hbConnectorsSearchAll {
    hbConnectorsSearchAll {
      totalCount
      data {
        id
        created
        updated
        name
        status
        format
        updatedBy
        user
        code
        numericId
        comments
        params {
          name
          label
          defaultValue
          defaultValueLabel
          required
          type
          allowedValues {
            label
            value
          }
        }
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlatformsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(
                setSettingsTabAction({
                  platforms: data.hbConnectorsSearchAll?.data ?? [],
                }),
              ),
            ];
          }

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

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