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

import { GET_ACCOUNTS } from '@/graphql/services/customReports/constants';

import { PAYLOAD_NAME } from '@/graphql/services/customReports/types/payload/accounts';

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

const query = `
  query ${GET_ACCOUNTS}($payload: ${PAYLOAD_NAME}) {
    ${GET_ACCOUNTS}(payload: $payload) {
      id
      name
      publishers {
        id
        name
      }
    }
  }
`;

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

export default (action$) =>
  action$.pipe(
    ofType(getAccountOptionsAction.type),
    switchMap((action) => {
      const { searchText = '' } = action.payload ?? {};

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText,
            pageSize: 30,
          },
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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

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