import { ofType } from 'redux-observable';
import { concat, defer, EMPTY } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

import { GENERATE_TOKEN } from '@/graphql/services/users/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/apiToken';

import { generateTokenAction } from '../slices';
import copyToClipboard from '@/modules/@common/helpers/copy';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ${GENERATE_TOKEN}($payload: ${PAYLOAD_NAME}) {
    ${GENERATE_TOKEN}(payload: $payload){
      access
      refresh
    }
  }
`;

const getResponse = ({ data }) => data[GENERATE_TOKEN];

export default (action$) =>
  action$.pipe(
    ofType(generateTokenAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            accountId: action.payload.accountId,
            userId: action.payload.userId,
            expirationDate: action.payload.expirationDate,
            resources: action.payload.resources,
            isExpirationDateActive: action.payload.isExpirationDateActive,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return defer(() => copyToClipboard(JSON.stringify(getResponse(response), null, ' '))).pipe(
              map(() =>
                notifyAction({
                  type: TYPE_SUCCESS,
                  message: 'Access and Refresh tokens were copied to Clipboard',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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