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

import { editCustomCategoryAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation labelUpdateMutation(
    $id: String!,
    $color: String!
    $name: String!
  ) {
    labelUpdate(
      id: $id
      color: $color
      name: $name
    ) {
      uid
      name
      color
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(editCustomCategoryAction.type),
    switchMap((action) => {
      const { id, color, name, callbackAfterCreate } = action.payload;
      const categoryForUpdate = { id, color, name };
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: categoryForUpdate,
      }).pipe(
        tap(({ errors }) => {
          if (!errors.length) {
            callbackAfterCreate(categoryForUpdate);
          }

          return EMPTY;
        }),
        switchMap(() => EMPTY),
      );

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