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

import { GET_XRAY_CAMPAIGNS_ADVERTISER_OPTIONS } from '@/graphql/services/xRayCampaings/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayCampaings/types/payload/advertiser';

import { getAdvertiserOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_XRAY_CAMPAIGNS_ADVERTISER_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_CAMPAIGNS_ADVERTISER_OPTIONS}(payload: $payload) {
      records {
        id
        name
     }   
    }
  }
`;

const getResponse = ({ data }) => data[GET_XRAY_CAMPAIGNS_ADVERTISER_OPTIONS].records;

export default (action$) =>
  action$.pipe(
    ofType(getAdvertiserOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            search: action.payload ?? '',
            pageSize: 30,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                advertiserOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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