import notification from './notification'

import { OkResponse, Response } from 'redux/Common/types'
import { Maybe } from 'types/utilities'

/**
 * Validate if the response is successful, because the API was apparently typed by a gerbil.
 *
 * @param {unknown} res Potential response from the API
 * @returns {res is OkResponse<T>} Whether the response is a successful response
 */
export const isSuccessfulResponse = <T>(res: unknown): res is OkResponse<T> =>
  typeof res === 'object' && res !== null && 'ok' in res && 'response' in res

/**
 * Get the API response, or show an error notification if the response is not successful.
 *
 * @param {Response<T>} res Response from the API
 * @returns {Maybe<T>} The API response, or nothing if the response is not successful
 */
export const getApiResponse = async <T>(
  res: Promise<Response<T>>
): Promise<Maybe<T>> => {
  const response = await res
  if (!isSuccessfulResponse<T>(response)) {
    return void notification.error({ message: response?.message })
  }

  return response.response
}
