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

import { mapApiError } from '@/modules/@common/constants/mapApiError';

import { createCustomCategoryAction, getCustomCategoriesOptionsAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation labelCreateMutation($label: LabelInputType!) {
    labelCreate(label: $label) {
      uid
      name
      color
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(createCustomCategoryAction.type),
    switchMap((action) => {
      const {
        payload: { category, contentOwner },
      } = action;

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: {
            label: {
              name: category.label,
              color: category.color,
              contentOwnerId: contentOwner,
            },
          },
        },
        {
          mapError: mapApiError({
            categoryName: category.label,
          }),
        },
      ).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { uid } = data.labelCreate;
            actions.push(
              of(
                setStateAction({
                  selectedCategory: { ...category, id: uid },
                }),
              ),
              of(getCustomCategoriesOptionsAction({ contentOwner })),
            );
          }

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

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