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

import { deleteCustomReportAction, getCustomReportsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation deleteCustomReport(
    $id: Int!
  ) {
    deleteCustomReport(
      id: $id
    ) {
      id
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(deleteCustomReportAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(getCustomReportsAction()));
          }
          return concat(...actions);
        }),
      );

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