type UnsuccessfulResponse = {
  data?: {
    client_secret?: string,
    redirect_to_url?: string,
    use_stripe_sdk?: string,
  },
  reason: string,
}

export enum PaymentActions {
  ThreeDSecure,
  Redirect,
}

export type OnFailedPaymentActionData = {
  action: PaymentActions,
  value: string,
}

export const handleUnsuccessfulSubscription = ({ data, reason }: UnsuccessfulResponse) => {
  const clientSecret = data?.use_stripe_sdk || data?.client_secret
  if (reason === 'requires_action' && clientSecret) {
    const actionData: OnFailedPaymentActionData = {
      action: PaymentActions.ThreeDSecure,
      value: clientSecret,
    }
    return Promise.reject(actionData)
  }

  if (reason === 'requires_action' && data?.redirect_to_url) {
    const actionData: OnFailedPaymentActionData = {
      action: PaymentActions.Redirect,
      value: data.redirect_to_url,
    }
    return Promise.reject(actionData)
  }

  return Promise.reject()
}
