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

import { TEMPLATE_ACCOUNT_ALL } from '@/modules/forms/constants';

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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(getAccountOptionsAction.type),
    switchMap((action) => {
      const autocomplete = selectors.autocompleteSelector(state$.value);

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

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

            if (!action.payload?.length) {
              textOptions.unshift(TEMPLATE_ACCOUNT_ALL);
            }

            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions,
                  },
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
