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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createKeyListAction.type),
    switchMap(() => {
      const state = state$.value;

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

      const stream$ = gqlRequest({
        query,
        variables: {
          name,
          daccountId: demandAccount.value,
          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$);
    }),
  );
