defmodule TarakanWeb.BillingController do
  @moduledoc """
  Stripe exit points for subscription billing.

  Plain POST endpoints (authenticated) that create a Checkout or Billing
  Portal session and 303-redirect to Stripe. LiveViews use the same
  `Tarakan.Billing` functions directly; these exist for non-LiveView pages
  like /pricing.
  """

  use TarakanWeb, :controller

  alias Tarakan.Billing

  def checkout(conn, %{"plan" => plan}) do
    case Billing.ensure_checkout(conn.assigns.current_scope, plan) do
      {:ok, checkout_url} ->
        redirect(conn, external: checkout_url)

      {:error, _reason} ->
        conn
        |> put_flash(:error, "Checkout could not be started. Try again shortly.")
        |> redirect(to: ~p"/pricing")
    end
  end

  def checkout(conn, _params), do: checkout(conn, %{"plan" => "enterprise"})

  def portal(conn, _params) do
    case Billing.portal_session(conn.assigns.current_scope.account) do
      {:ok, portal_url} ->
        redirect(conn, external: portal_url)

      {:error, _reason} ->
        conn
        |> put_flash(:error, "The billing portal is unavailable for this account.")
        |> redirect(to: ~p"/accounts/billing")
    end
  end
end
