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

import * as selectors from '../selectors';
import { getConnectorsAction, updateConnectorAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation updateHBConnector(
    $id: String,
    $name: String,
    $code: String,
    $status: String,
    $format: String,
    $comments: String,
    $params: [MarketplaceHBParamInputType]
  ) {
    updateHBConnector(
      id: $id,
      name: $name,
      code: $code,
      status: $status,
      format: $format,
      comments: $comments,
      params: $params
    ) {
      id
      created
      updated
      name
      updatedBy
      status
      format
      code
      numericId
      comments
      params {
        name
        label
        defaultValue
        defaultValueLabel
        required
        type
        allowedValues {
          label
          value
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateConnectorAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const state = state$.value;

      const name = selectors.nameSelector(state);
      const code = selectors.codeSelector(state);
      const status = selectors.statusSelector(state);
      const format = selectors.formatSelector(state);
      const parameters = selectors.parametersSelector(state);
      const comments = selectors.commentsSelector(state);

      let requestParams = {
        comments,
      };

      if (code?.length) {
        requestParams = {
          ...requestParams,
          code,
        };
      }

      const parsedParams = JSON.parse(parameters);

      if (Object.keys(parsedParams).length !== 0) {
        if (parsedParams?.params && Array.isArray(parsedParams?.params)) {
          requestParams = {
            ...requestParams,
            params: [...parsedParams.params],
          };
        } else {
          requestParams = {
            ...requestParams,
            params: [parsedParams],
          };
        }
      }

      if (format?.length) {
        requestParams = {
          ...requestParams,
          format,
        };
      }
      if (status?.length) {
        requestParams = {
          ...requestParams,
          status,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
          name,
          ...requestParams,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(getConnectorsAction()));
            Router.push('/hb-connectors');
          }
          return concat(...actions);
        }),
      );

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