import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { EMPTY, of, timer } from 'rxjs';
import { debounce, filter, switchMap } from 'rxjs/operators';

import { watchHubSelector } from '../selectors';
import { getSupplyTagOptionsAction, updateStoreByPropAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';

import type { RootState } from '@/modules/@common/store/store';

export type RequestPayloadType = {
  searchText?: string;
  pageSize: number;
  siteIds?: number[];
};

type ResponseType = {
  data: {
    id: string;
    name: string;
  }[];
};

type ActionPayload = {
  searchText: string;
};

const queryName = 'watchGetSupplyTags' as const;

const getResponse = (data: ResponseType) => data.data;

const query = `
  query WatchGetSupplyTags(
    $pageSize: Int,
    $searchText: String,
    $siteIds: [Int],
  ) {
    ${queryName}(
      pageSize: $pageSize,
      searchText: $searchText,
      siteIds: $siteIds,
    ) {
      data {
        id
        name
      }
    }
  }
`;

const getSupplyTagOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getSupplyTagOptionsAction> =>
        action.type === getSupplyTagOptionsAction.type,
    ),
    debounce((action) => {
      if (!action.payload) {
        return timer(0);
      }
      const { searchText = '' } = action.payload;
      return timer(searchText.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actionPayload = action.payload! as ActionPayload;
      const watchHub = watchHubSelector(state$.value);
      const payload: RequestPayloadType = {
        searchText: actionPayload.searchText || '',
        pageSize: 30,
      };

      if (watchHub?.id) {
        payload.siteIds = [watchHub.id];
      }

      return gqlRequest({
        query,
        variables: payload,
      }).pipe(
        switchMap((response: GraphQLResponse<typeof queryName, ResponseType>) => {
          if (!response.errors.length) {
            return of(
              updateStoreByPropAction({
                supplyTagOptions: getResponse(response.data[queryName]),
              }),
            );
          }
          return EMPTY;
        }),
      );
    }),
  );

export default getSupplyTagOptionsEpic;
