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

import { UPDATE_CONTENT_OWNER } from '@/graphql/services/accounts/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/accounts/types/payload/contentOwner';

import { getDataAction as getContentOwnerDataAction, updateContentOwner } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$) =>
  action$.pipe(
    ofType(updateContentOwner.type),
    switchMap((action) => {
      const { callback, ...payload } = action.payload;
      const stream$ = gqlRequest({
        query,
        variables: {
          payload,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(getContentOwnerDataAction(payload.accountId)),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Content owner updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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