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

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

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

const query = `
  mutation UpdateEntity(
    $entity: EntitiesModuleUpdateInputType
  ) {
    updateEntity(
      entity: $entity
    ) {
      uid,
      status,
      category,
      created,
      updated,
      value,
      source,
      keywords {
        lang,
        value,
        suggestions,
      }
      metaData {
        birthDate
        iab
      }
      types
      notUpdated
      errorMessage
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(updateEntityAction.type),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          entity: {
            id: payload.id,
            status: payload.status,
            thumbnailFileUrl: payload.thumbnailFileUrl,
            types: payload.types,
            metaData: {
              ...(payload.metaData?.birthDate && { birthDate: payload.metaData?.birthDate }),
              ...(payload.metaData?.iab && { iab: payload.metaData?.iab }),
            },
            keywords: payload.keywords,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const notUpdatedWeavo = response.data.updateEntity.notUpdated;
            const weavoErrorMessage = response.data.updateEntity.errorMessage;
            if (notUpdatedWeavo) {
              const notUpdatedEntity = response.data.updateEntity;
              delete notUpdatedEntity.notUpdated;
              delete notUpdatedEntity.errorMessage;
              return concat(
                of(
                  showNotificationAction({
                    type: TYPE_ERROR,
                    message: weavoErrorMessage,
                  }),
                ),
                of(updateLocalEntityAction({ ...payload, ...notUpdatedEntity })),
              );
            }
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Entity Updated',
                }),
              ),
              of(updateLocalEntityAction({ ...payload, ...response.data.updateEntity })),
            );
          }

          return EMPTY;
        }),
      );

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