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

import { getAccountFeatures, updateStoreByPropAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query accountFeaturesQuery($accountId: Int!) {
    accountFeatures(accountId: $accountId){
      name
      value
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getAccountFeatures.type),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          accountId: payload,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const accountFeatures = response.data.accountFeatures.reduce((acc, feature) => {
              acc[feature.name] = feature.value;
              return acc;
            }, {});
            actions.push(of(updateStoreByPropAction({ accountFeatures })));
          }

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

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