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

import { getAvailableKeyByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query availableKeyById(
    $id: String
  ) {
    availableKeyById(
      id: $id
    ) {
      id
      created
      updated
      name
      key
      status
      updatedBy
      user
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getAvailableKeyByIdAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { name, key } = data.availableKeyById;

            actions.push(
              of(
                setFieldAction({
                  keyName: name,
                  keyValue: key,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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