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

import { getDestinationParams } from '../../helpers/computedState';
import { clearFormAction, updateDestinationAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation updateDestination(
    $id: Int!,
    $type: String!,
    $name: String!,
    $publisherId: Int!,
    $visibility: String!,
    $defaultChannel: String,
    $defaultChannelName: String,
    $defaultPlaylist: String,
    $defaultPlaylistName: String,
    $title: Boolean,
    $description: Boolean,
    $thumbnail: Boolean,
    $category: Boolean,
    $manualTags: Boolean,
    $autoTags: Boolean,
    $closedCaptions: Boolean,
    $language: Boolean,
    $status: String!,
    $accessToken: String!,
    $refreshToken: String,
    $expiryDate: String!
  ) {
    updateDestination(
      id: $id,
      name: $name,
      type: $type,
      publisherId: $publisherId,
      visibility: $visibility,
      defaultChannel: $defaultChannel,
      defaultChannelName: $defaultChannelName,
      defaultPlaylist: $defaultPlaylist,
      defaultPlaylistName: $defaultPlaylistName,
      title: $title,
      description: $description,
      thumbnail: $thumbnail,
      category: $category,
      manualTags: $manualTags,
      autoTags: $autoTags,
      closedCaptions: $closedCaptions,
      language: $language,
      status: $status,
      accessToken: $accessToken,
      refreshToken: $refreshToken,
      expiryDate: $expiryDate
    ){
      id
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateDestinationAction.type),
    switchMap(({ payload }) => {
      const params = {
        ...getDestinationParams(state$.value),
      };

      if (!params.title) {
        params.title = true;
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...params,
          id: payload,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            Router.push('/publishing');
            actions.push(of(clearFormAction()));
          }

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

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