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

import { CREATE_ITEM } from '../../../../../graphql/services/contentOwners/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '../../../../../graphql/services/contentOwners/types/payload/item';

import * as selectors from '../selectors';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `mutation ${CREATE_ITEM}($payload: ${PAYLOAD_NAME}) {
  ${CREATE_ITEM}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap(() => {
      const name = selectors.nameSelector(state$.value);
      const salesforceId = selectors.salesforceIdSelector(state$.value);
      const comments = selectors.commentsSelector(state$.value);
      const playFromCo = selectors.playFromCoSelector(state$.value);
      const callToAction = selectors.callToActionSelector(state$.value);
      const type = selectors.typeSelector(state$.value);
      const status = selectors.statusSelector(state$.value);
      const isPublic = selectors.isPublicSelector(state$.value);
      const feedPriority = selectors.feedPrioritySelector(state$.value);
      const account = selectors.accountSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            name,
            salesforceId,
            comments,
            playFromCo,
            callToAction,
            type,
            status: status ? 1 : 0,
            isPublic: isPublic ? 1 : 0,
            feedPriority: +feedPriority,
            accountId: account.id,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/content-owners');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Content owner created',
              }),
            );
          }

          return EMPTY;
        }),
      );

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