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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { getDestinationParams } from '../../helpers/computedState';
import { clearFormAction, createDestinationAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

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

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

          if (!errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Destination created',
                }),
              ),
            );
            Router.push('/publishing');
            actions.push(of(clearFormAction()));
          }

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

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