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 { deleteAccessUsersAction, setIsLoadingAction, updateStateByParamAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(deleteAccessUsersAction.type),
    filter((action) => !!action.payload?.length),
    switchMap((action) => {
      const videoId = selectors.videoIdSelector(state$.value);
      const accessUsers = selectors.accessUsersSelector(state$.value);
      const usersToDelete = action.payload;
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId,
          users: usersToDelete.map((id) => ({
            id: `${id}`,
            role: ACCESS_USER_ROLES.read,
          })),
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                updateStateByParamAction({
                  accessUsers: accessUsers.filter((user) => !usersToDelete.includes(user.id)),
                }),
              ),
            );
          }

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

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