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

import { CREATE_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 { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import {
  accountSelector,
  descriptionSelector,
  enabledSelector,
  iconSelector,
  lookerReportIdSelector,
  publisherIdsSelector,
  uiNameSelector,
} from '@/modules/customReports/Editor/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap(() => {
      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: {
            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 of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Dashboard created',
              }),
            );
          }

          return EMPTY;
        }),
      );

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