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

import * as selectors from '../selectors';
import { getInfoAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

export default (action$, state$) =>
  action$.pipe(
    ofType(getInfoAction.type),
    filter(() => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);

      return !!pageConfig;
    }),
    switchMap(({ payload }) => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);

      const stream$ = gqlRequest({
        query: pageConfig.infoQuery,
        variables: {
          id: payload,
        },
      }).pipe(
        switchMap(({ data = {}, errors }) => {
          let actions = [];

          if (!errors?.length) {
            actions = [
              of(
                setFieldAction({
                  info: {
                    ...data.supplyAccountById,
                    ...data.demandAccountById,
                    ...data.siteById,
                    ...data.supplyTagById,
                    ...data.demandTagById,
                    ...data.advertiserById,
                  },
                }),
              ),
            ];
          }

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

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