import { ofType } 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';

const queryGQL = `
  query videoDestinationsSearch(
    $search: String,
    $platform: String,
    $publisherIds: [Int],
    $page: Int,
    $pageSize: Int,
    $sortBy: String,
    $sortOrder: String,
    $status: String,
    $name: String
    ) {
    videoDestinationsSearch(
      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
        }
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(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?.videoDestinationsSearch?.recordsTotal || 0;
          const records = data?.videoDestinationsSearch?.records || [];

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

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