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

import { UPDATE_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 { updateBody } from '../../helpers/buildBody';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const body = updateBody(state$.value);
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id: action.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: 'Updated',
              }),
            );
          }

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

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

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