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

import { CREATE_XRAY_LINE_ITEM } from '@/graphql/services/xRayLineItems/constants';
import { TYPE_ERROR, TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayLineItems/types/payload/xRayLineItemUpsert';

import { createBody } from '../../helpers/buildBody';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `mutation ${CREATE_XRAY_LINE_ITEM}($payload: ${PAYLOAD_NAME}) {
  ${CREATE_XRAY_LINE_ITEM}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap(() => {
      const body = createBody(state$.value);
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              ...body,
            },
          },
        },
        { showNotificationMessage: false },
      ).pipe(
        switchMap((response) => {
          const error = response.errors?.[0];
          if (!error) {
            Router.push('/x-ray/line-items');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Created',
              }),
            );
          }

          const message =
            error?.response?.status === 409
              ? `An X-Ray Line Item with name ${body.name} already exists`
              : "Can't create X-Ray Line";

          return of(
            showNotificationAction({
              type: TYPE_ERROR,
              message,
            }),
          );
        }),
      );

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