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

import { DEMAND_ACCOUNT_PAGE_INFO_GRAPHQL_QUERY } from '../../constants';

import { getDemandAccountByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

export default (action$) =>
  action$.pipe(
    ofType(getDemandAccountByIdAction.type),
    switchMap(() => {
      const demandAccountId = Router.query.params[0];

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

          if (!errors?.length) {
            actions = [
              of(
                setFieldAction({
                  demandAccountInfo: { ...data.demandAccountById },
                }),
              ),
            ];
          }

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

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