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

import { UPDATE_ITEM } from '@/graphql/services/customReports/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/customReports/types/payload/item';

import {
  accountSelector,
  descriptionSelector,
  enabledSelector,
  iconSelector,
  lookerReportIdSelector,
  publisherIdsSelector,
  uiNameSelector,
} from '../selectors';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const account = accountSelector(state$.value);
      const description = descriptionSelector(state$.value);
      const enabled = enabledSelector(state$.value);
      const lookerReportId = lookerReportIdSelector(state$.value);
      const publisherIds = publisherIdsSelector(state$.value);
      const uiName = uiNameSelector(state$.value);
      const icon = iconSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: action.payload,
            accountId: account.id,
            allSites: !publisherIds.length ? 1 : 0,
            description,
            enabled,
            lookerReportId,
            publisherIds,
            uiName,
            icon,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/custom-reports');

            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Dashboard updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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