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

const query = `
  mutation updateKeyList(
    $id: String,
    $name: String,
    $status: String,
    $keys: [String]
  ) {
    updateKeyList(
      id: $id,
      name: $name,
      status: $status,
      keys: $keys
    ) {
      id
      created
      updated
      name
      keys
      count
      status
      updatedBy
    }
  }
`;

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

      const name = selectors.nameSelector(state);
      const keys = selectors.keysSelector(state);

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

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

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