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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createConnectorAction.type),
    switchMap(() => {
      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 params = [];

      const parsedParams = JSON.parse(parameters);

      if (parsedParams?.params && Array.isArray(parsedParams?.params)) {
        params = [...params, ...parsedParams.params];
      } else {
        params = [parsedParams];
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          name,
          code,
          status,
          format,
          params,
          comments,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

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

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