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

import { GET_XRAY_LINE_ITEM_LABEL_OPTIONS } from '@/graphql/services/xRayLineItems/constants';

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

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

const query = `
  query ${GET_XRAY_LINE_ITEM_LABEL_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_XRAY_LINE_ITEM_LABEL_OPTIONS}(payload: $payload) {
      records {
        name
        values {
          value
        }
        color
        labelId
     }   
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_XRAY_LINE_ITEM_LABEL_OPTIONS].records.reduce((acc, curr) => {
    const labels = curr.values
      ? curr.values.map((label) => ({
          label: label.value,
          value: `${curr.labelId}|${label.value}`,
          name: curr.name,
          color: curr.color,
          groupBy: `${curr.name}|${curr.labelId}|${curr.color}`,
          labelId: curr.labelId,
          taxonomyId: curr.labelId,
        }))
      : [];

    return [...acc, ...labels];
  }, []);

export default (action$, state$) =>
  action$.pipe(
    ofType(getLabelsOptionsAction.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,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                labelsOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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