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

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

const query = `
  query analyticsAccounts(
    $searchText: String,
    $pageSize: Int
  ) {
    analyticsAccounts(
      searchText: $searchText,
      pageSize: $pageSize,
    ) {
      id
      name
      salesforceId
    }
  }
`;

const getResponse = ({ data: { analyticsAccounts } }) =>
  analyticsAccounts.map((account) => ({
    value: account.salesforceId,
    label: account.name,
    salesforceId: account.salesforceId,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getAccountOptionsAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload ?? '',
          pageSize: 30,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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

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