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

import { TAXONOMY_KEYWORDS } from '../../constants';
import { GET_XRAY_LINE_ITEM_TAXONOMY_OPTIONS } from '@/graphql/services/xRayLineItems/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayLineItems/types/payload/taxonomy';

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

const query = `
  query ${GET_XRAY_LINE_ITEM_TAXONOMY_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_LINE_ITEM_TAXONOMY_OPTIONS}(payload: $payload) {
      records {
        taxonomyId
        value
     }   
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_XRAY_LINE_ITEM_TAXONOMY_OPTIONS].records.map((o) => ({
    label: o.value,
    value: o.taxonomyId,
    taxonomyId: o.taxonomyId,
  }));

export default (action$, state$) =>
  action$.pipe(
    ofType(getKeywordsOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search?.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const publisherId = hubSelector(state$.value)?.id;

      if (!publisherId) {
        return EMPTY;
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText: action.payload ?? '',
            pageSize: 30,
            publisherId,
            category: TAXONOMY_KEYWORDS,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                keywordsOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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