import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { debounceTime, filter, switchMap } from 'rxjs/operators';

import { getDestinationsAction, setDestinationsAction, setTotalDestinationsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

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

const queryGQL = `
  query destinationsSearch(
    $search: String,
    $platform: String,
    $publisherIds: [Int],
    $page: Int,
    $pageSize: Int,
    $sortBy: String,
    $sortOrder: String,
    $status: String,
    $name: String
    ) {
    destinationsSearch(
      search: $search,
      platform: $platform,
      publisherIds: $publisherIds,
      page: $page,
      pageSize: $pageSize,
      sortBy: $sortBy,
      sortOrder: $sortOrder,
      status: $status,
      name: $name,
      ) {
      recordsTotal
      page
      pageSize
      records {
        id
        type
        name
        visibility
        defaultChannel
        defaultChannelName
        defaultPlaylist
        defaultPlaylistName
        closedCaptions
        title
        description
        thumbnail
        category
        manualTags
        autoTags
        language
        status
        videos
        updatedAt
        publisher {
          name,
          id
        }
      }
    }
  }
`;

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getDestinationsAction> => action.type === getDestinationsAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap((action) => {
      const variables = { ...action.payload };

      if (action.payload.publisherId) {
        variables.publisherIds = [action.payload.publisherId];
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables,
      }).pipe(
        switchMap(({ data }) => {
          const recordsTotal = data?.destinationsSearch?.recordsTotal || 0;
          const records = data?.destinationsSearch?.records || [];

          return concat(of(setTotalDestinationsAction(recordsTotal)), of(setDestinationsAction(records)));
        }),
      );

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

export default epic;
