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

import { accountListAction, accountListLoadingAction, accountSearchPrefixAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

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

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

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

            actions.push(of(accountListAction(accountOptions)));
          }

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

      return concat(of(accountListLoadingAction(true)), stream$, of(accountListLoadingAction(false)));
    }),
  );
