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

import { videoSelector } from '../selectors';
import { videoDeleteAction, videoDeleteEventAction, videoDeleteProgressAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation videoDeleteMutation($id: String!) {
    videoDelete(id: $id) {
      result
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(videoDeleteAction.type),
    switchMap(() => {
      const state = state$.value;
      const { uid } = videoSelector(state);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [of(videoDeleteProgressAction(false))];

          if (!errors.length) {
            const { videoDelete } = data;

            if (videoDelete.result) {
              actions.push(of(videoDeleteEventAction()));
            }
          }

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

      return concat(of(videoDeleteProgressAction(true)), stream$);
    }),
  );
