class Family::FinancialAid::Stripe::SessionsController < Family::Controller
  def show
    render_success :ok, json: stripe_session('show')
  end

  def create
    if stripe_session_id
      show
    elsif stripe_session && application.update(stripe_session_id: stripe_session['id'])
      render_success :ok, json: stripe_session
    else
      render_error :unprocessable_entity
    end
  end

  private
    def current_admission_year
      current_school.find_or_build_admission_config.school_year
    end

    def application
      @application ||= current_family.financial_aid_applications
        .find_or_initialize_by(school_year: current_admission_year)
    end

    def stripe_session_id
      application.stripe_session_id
    end

    def stripe_session(action = nil)
      @stripe_session ||= Stripe::CheckoutSessionService
        .call(
          application,
          action || action_name,
          stripe_session_id,
          line_item: { quantity: 1, price: Rails.application.secrets.stripe[:price] }
        )
    end
end
