import fetch from 'isomorphic-fetch';

import { getSession } from './session';
import { getAuthKey, handleAPIResponse } from 'utils/session';
import { formatPlan, formatBillingErrors, expirationError } from 'utils/billing';
import { routeActions } from 'redux-simple-router';

export const SUBMIT_CHECKOUT = 'SUBMIT_CHECKOUT';
function submitCheckout() {
  return {
    type: SUBMIT_CHECKOUT
  };
}

export const BILLING_ERROR = 'BILLING_ERROR';
function billingError(error) {
  return {
    type: BILLING_ERROR,
    error
  };
}

export function makePurchase(StripeToken, plan) {
  return dispatch => {
    const authKey = getAuthKey();

    fetch(process.env.PRO_API + '/plan/' + plan + '/purchase/', {
      headers: {'accept': 'application/json', 'content-type': 'application/json', 'x-session-key': authKey},
      body: JSON.stringify({ StripeToken }),
      method: 'post'
    })
    .then(handleAPIResponse)
    .then(data => dispatch(getSession()))
    .then(data => dispatch(routeActions.replace('/dashboard/?modal=purchase_confirmation')))
    .catch(response => {
      const err = formatBillingErrors(response);
      dispatch(billingError(err));
    });
  };
}

export function attemptPurchase(name, number, cvc, exp, plan, occurrence) {
  return dispatch => {
    dispatch(submitCheckout());

    const paymentInfo = {
      name,
      number,
      cvc,
      exp
    };

    // Make sure that the request is at least ~500ms for UI purposes
    setTimeout(() => {
      // validate expiry before trying to create token
      // stripe does this client side before allowing create token request
      if (!Stripe.card.validateExpiry(exp)) {
        const err = expirationError();
        return dispatch(billingError(err));
      }

      Stripe.card.createToken(paymentInfo, (status, response) => {
        const { error, id } = response;

        if (error) {
          const err = formatBillingErrors(error);
          dispatch(billingError(err));
        } else {
          const stripePlan = formatPlan(plan, occurrence);
          dispatch(makePurchase(id, stripePlan));
        }
      });
    }, 500);
  };
}
