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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { addEntityAction, createEntityAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation CreateEntity(
    $entity: EntitiesModuleCreateInputType
  ) {
    createEntity(
      entity: $entity
    ) {
      uid,
      status,
      category,
      created,
      updated,
      value,
      keywords {
        lang,
        value,
        suggestions,
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(createEntityAction.type),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          entity: {
            status: payload.status,
            keywords: payload.keywords,
            category: payload.category,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Entity Created',
                }),
              ),
              of(addEntityAction({ ...response.data.createEntity, id: response.data.createEntity.uid })),
            );
          }
          return EMPTY;
        }),
      );

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