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

import { ACCESS_USER_ROLES } from '../../constants';

import * as selectors from '../selectors';
import { copyAccessUsersToTrimedVideoAction, setIsLoadingAction, updateStateByParamAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation accessAddUsers(
    $videoId: String,
    $users: [AccessUserDeleteType],
  ) {
    accessAddUsers(
      videoId: $videoId,
      users: $users,
    ) {
      data
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(copyAccessUsersToTrimedVideoAction.type),
    filter((action) => !!action.payload?.length),
    switchMap((action) => {
      const videoId = selectors.videoIdSelector(state$.value);
      const accessUsers = selectors.accessUsersSelector(state$.value);
      const copiedUsers = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId,
          users: copiedUsers.map((user) => ({
            id: `${user.id}`,
            role: user.role,
          })),
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                updateStateByParamAction({
                  accessUsers: [accessUsers.find((user) => user.role === ACCESS_USER_ROLES.owner), ...copiedUsers],
                }),
              ),
            );
          }

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

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