import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { getDestinationByIdAction, setDestinationDataAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getDestinationById($id: Int!) {
    getDestinationById(id: $id) {
      id
      type
      name
      publisherId
      visibility
      defaultChannel
      defaultPlaylist
      defaultChannelName
      defaultPlaylistName
      title
      description
      thumbnail
      category
      manualTags
      autoTags
      closedCaptions
      language
      status
      videos
      accessToken
      pageAccessToken
      refreshToken
      expiryDate
      createdAt
      updatedAt
      userName
      publisher {
        name
      }
      channels {
        id
        title
      }
      playlists {
        id
        title
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getDestinationByIdAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...action.payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (errors.length) {
            Router.push('/publishing');
          } else {
            actions.push(of(setDestinationDataAction(data.getDestinationById)));
          }

          return concat(...actions);
        }),
      );

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