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

import { TYPE_BUSINESS, TYPE_PUBLISHER, TYPE_SYNDICATION, TYPE_VAST } from '@/modules/@common/constants/account';

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

const query = `
  query getHubsAccountsOptions(
    $searchText: String,
    $pageSize: Int,
    $filtersValues: [String]
  ) {
    getHubsAccountsOptions(
      searchText: $searchText,
      pageSize: $pageSize,
      filtersValues: $filtersValues, 
    ) {
      id
      name
    }
  }
`;

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

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

      const stream$ = gqlRequest({
        query,
        variables: {
          searchText,
          pageSize: 30,
          filtersValues: isSyndicationOnly ? [TYPE_SYNDICATION] : [TYPE_PUBLISHER, TYPE_BUSINESS, TYPE_VAST],
        },
      }).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$,
      );
    }),
  );
