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 { dataSelector } from '../selectors';
import { mergeEntitiesAction, setAction, setTableAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(mergeEntitiesAction.type),
    switchMap(({ payload }) => {
      const { entitiesForMerge, primary, alias, callback } = payload;
      const currentData = dataSelector(state$.value);
      const entity = {
        primary,
        secondary: entitiesForMerge
          .filter((entity$) => entity$.id !== primary)
          .map((entity$) => ({
            id: entity$.id,
            saveAsAlias: alias.includes(entity$.id),
          })),
      };
      const stream$ = gqlRequest({
        query,
        variables: { entity },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const updatedPrimaryEntity = { ...response.data.mergeEntity, id: response.data.mergeEntity.uid };
            const updatedData = currentData.reduce((acc, entity$) => {
              if (entity$.id === primary) {
                acc.push({ ...entity$, ...updatedPrimaryEntity });
              } else if (!entitiesForMerge.some((entityForMerge) => entityForMerge.id === entity$.id)) {
                acc.push(entity$);
              }
              return acc;
            }, []);

            callback();

            return concat(
              of(setTableAction({ data: updatedData })),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message:
                    'The merging process has been started. The primary entity and the videos will be updated soon',
                }),
              ),
            );
          }
          return EMPTY;
        }),
      );

      return concat(of(setAction({ isMergeLoading: true })), stream$, of(setAction({ isMergeLoading: false })));
    }),
  );
