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

import { getAccountsAction, getHubsAndDemandAccountsAction, setHubsAndDemandAccountsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query MarketplaceHubsAndDemandAccounts {
    hubsAndDemandAccounts {
      records {
        id
        name
        mpSelfService
        accountId
        demandAccountId
        demandAccount {
          id
          name
        }
      }
    }
  }
`;

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

          if (!errors.length) {
            const demandAccounts = hubsAndDemandAccounts.records?.map((item) => item?.demandAccount);

            actions = [
              of(
                setHubsAndDemandAccountsAction({
                  userHubs: hubsAndDemandAccounts.records,
                  userDemandAccounts: Object.values(
                    demandAccounts.reduce((acc, obj) => ({ ...acc, [obj.id]: obj }), {}),
                  ),
                }),
              ),
            ];
          }

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

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