class CoinbaseController < ApplicationController

  before_action :create_payment_notification, only: [:callback]

  # Order callback when transaction is completed by user.
  # Create Order from ShoppingCart if everything checks out.
  def callback
    Transaction::Order::Coinbase.create_from_payment_notification notification_id: @notification.id
    head :ok
  end

  # User is redirected here after successful payment.
  # Find notification with the order to generate frontend receipt URL
  def success
    # Find shopping cart from ID that is added to checkout page params.
    # Checkout URL is generated by ShoppingCart#create_coinbase_checkout_url
    cart = ShoppingCart.find_by(id: params[:shopping_cart_id])

    if cart && cart.order.present?
      redirect_to cart.order.www_receipt_url
    else
      redirect_to Api::Application.config.www_receipts_url
    end
  end

private

  def create_payment_notification
    secret_matched = params[:secret] == Api::Application.config.coinbase_secret
    @notification = PaymentNotification::Coinbase.process_raw_post request.raw_post, secret_matched: secret_matched
  end

end
