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

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

const query = `
  query SearchDemandAccountsQuery(
    $from: Int,
    $size: Int,
    $query: String,
    $status: String
  ) {
    searchDemandAccounts(
      from: $from,
      size: $size,
      query: $query,
      status: $status
    ) {
      totalCount
      data {
        id
        name
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getDemandAccountsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      let params = {};

      if (action.payload?.length) {
        params = {
          ...params,
          query: action.payload,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          size: 30,
          from: 0,
          ...params,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                setFieldAction({
                  demandAccountOptions:
                    data.searchDemandAccounts?.data?.map((item) => ({
                      label: item.name,
                      value: item.id,
                    })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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