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

import { reloadSelectedVideoAction } from '../../../editorialVideoDetails/redux/slices';
import * as selectors from '../selectors';
import {
  setIsLoadingAction,
  setVideoSharedAction,
  shareVideoWithUsersAction,
  updateStateByParamAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query shareVideoWithUsers(
    $userIds: [Int],
    $message: String,
    $videoId: String,
    $videoUrl: String,
    $name: String,
  ) {
    shareVideoWithUsers(
      userIds: $userIds,
      message: $message,
      videoId: $videoId,
      videoUrl: $videoUrl,
      name: $name,
    ) {
      data
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(shareVideoWithUsersAction.type),
    switchMap((action) => {
      const usersToShare = selectors.usersToShareSelector(state$.value);
      const message = selectors.messageSelector(state$.value);
      const videoId = selectors.videoIdSelector(state$.value);
      const isUsedInTrim = selectors.isUsedInTrimSelector(state$.value);
      const accessUsers = selectors.accessUsersSelector(state$.value);

      const { url, name } = action.payload;

      const stream$ = gqlRequest({
        query,
        variables: {
          userIds: usersToShare.map((user) => parseInt(user.id, 10)),
          message,
          videoId,
          videoUrl: url,
          name,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            if (isUsedInTrim) {
              actions.push(
                of(
                  updateStateByParamAction({
                    accessUsers: [
                      ...accessUsers,
                      ...usersToShare.filter((user) => accessUsers.some((accessUser) => +user.id !== +accessUser.id)),
                    ],
                  }),
                ),
              );
            } else {
              actions.push(of(reloadSelectedVideoAction()));
            }

            actions.push(of(setVideoSharedAction()));
          }

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

      return concat(of(setIsLoadingAction(true)), stream$, of(setIsLoadingAction(false)));
    }),
  );
