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

import { GET_ADVERTISER_DM_ACCOUNTS_OPTIONS } from '../../../../../graphql/services/advertisers/constants';

import { getAccountOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_ADVERTISER_DM_ACCOUNTS_OPTIONS} {
    ${GET_ADVERTISER_DM_ACCOUNTS_OPTIONS} {
      id
      name
    }
  }
`;

const getResponse = ({ data }) => data[GET_ADVERTISER_DM_ACCOUNTS_OPTIONS];

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

          if (!response.errors.length) {
            const accountOptions = getResponse(response);

            actions.push(
              of(
                setAction({
                  accountOptions,
                }),
              ),
            );
          }

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

      return concat(
        of(
          setAction({
            accountOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
