class Family::Admissions::Stripe::SessionsController < Family::Controller
  include Family::Admissions::ApplicantScoped

  def show
    render_success :ok, json: stripe_session
  end

  def create
    if stripe_session
      render_success :ok, json: stripe_session
    else
      render_error :unprocessable_entity
    end
  end

  private
    def total_in_cents
      return 0 if params[:total].blank?

      (params[:total].to_f * 100).to_i
    end

    def processing_service
      @processing_service ||= Stripe::ProcessingService.new(current_school, total_in_cents)
    end

    def stripe_account_id
      @stripe_account_id ||= current_school.stripe_connect_account&.stripe_account_id
    end

    def options
      return { stripe_account: stripe_account_id } if action_name == 'show'

      {
        stripe_account: stripe_account_id,
        line_item: {
          quantity: 1,
          price_data: {
            currency: :usd,
            product_data: { name: "Admissions - #{applicant.full_name}" },
            unit_amount: processing_service.final_amount,
          }
        },
        payment_intent: {
          application_fee_amount: processing_service.sycamore_processing_fee,
          description: "Admissions - #{applicant.full_name}"
        }
      }
    end

    def stripe_session(action = nil)
      @stripe_session ||= Stripe::CheckoutSessionService
        .call(
          current_family,
          action_name,
          params[:id],
          options
        )
    end
end
