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 { searchAvailableKeysAction, updateAvailableKeyAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation updateAvailableKey(
    $id: String,
    $name: String,
    $key: String
  ) {
    updateAvailableKey(
      id: $id,
      name: $name,
      key: $key
    ) {
      id
      created
      updated
      name
      key
      status
      updatedBy
    }
  }
`;

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

      const name = selectors.keyNameSelector(state);
      const keyValue = selectors.keyValueSelector(state);

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

          if (!errors.length) {
            actions.push(of(searchAvailableKeysAction()));
            Router.push('/key-lists/keys');
          }
          return concat(...actions);
        }),
      );

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