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

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

import { addPublishEntriesAction, getPublishEntriesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  mutation videoCreatePublishEntry($destinations: [VideoPublishEntryInputType]) {
    videoCreatePublishEntry(destinations: $destinations) {
        data {
          id
          status
        }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(addPublishEntriesAction.type),
    switchMap((action) => {
      const { destinations, videoId } = action.payload;

      const paramsToSend = destinations
        .filter((dest) => dest.checked && !dest.published && dest.targetId && dest.targetName)
        .map((dest) => ({
          videoId,
          platform: dest.type,
          accountId: dest.id,
          target: {
            id: dest.targetId,
            name: dest.targetName,
            type: dest.targetType.toUpperCase(),
          },
          viewability: dest.visibility,
          settings: dest.settings,
          postText: dest.postText,
        }));

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

          if (!errors.length) {
            actions.push(
              of(getPublishEntriesAction(videoId)),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Video published',
                }),
              ),
            );
          }

          const corruptedDestinations = destinations.filter(
            (dest) => dest.checked && !dest.published && (!dest.targetId || !dest.targetName),
          );

          if (corruptedDestinations.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: `There are corrupted destinations (${corruptedDestinations.length})`,
                }),
              ),
            );
          }

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

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