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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(getKeyListsOptionsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);
      const { demandAccount } = pageConfig;

      let requestParams = {};

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

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

          if (!errors.length) {
            const { data: keyLists } = data.keyListsSearch;

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

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