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

import { getKeyNamesOptionsAction, setTargetingTabAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query availableKeysSearch(
    $from: Int,
    $size: Int,
    $query: String,
    $status: String,
    $sortBy: String,
    $sortOrder: String
  ) {
    availableKeysSearch(
      from: $from,
      size: $size,
      query: $query,
      status: $status,
      sortBy: $sortBy,
      sortOrder: $sortOrder
    ) {
      totalCount
      data {
        id
        created
        updated
        name
        keys
        count
        status
        updatedBy
        user
      }
    }
  }
`;

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

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

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

          if (!errors.length) {
            const { data: keys } = data.availableKeysSearch;

            actions.push(
              of(
                setTargetingTabAction({
                  keyNamesOptions: keys?.map((item) => ({ label: item.name, value: item.id })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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