defmodule BerrypodWeb.CheckoutSuccessController do
  @moduledoc """
  Handles the redirect back from Stripe checkout.

  This controller intercepts the Stripe redirect to set the email session
  cookie before forwarding to the checkout success LiveView. This allows
  customers to later view their orders and leave reviews without needing
  to re-verify their email.
  """

  use BerrypodWeb, :controller

  alias Berrypod.{EmailSession, Orders}

  def show(conn, %{"session_id" => session_id}) do
    # Look up the order to get the customer email
    order = Orders.get_order_by_stripe_session(session_id)

    conn =
      if order && order.customer_email do
        EmailSession.put_session(conn, order.customer_email)
      else
        conn
      end

    redirect(conn, to: R.checkout_success() <> "?session_id=#{session_id}")
  end

  def show(conn, _params) do
    redirect(conn, to: R.home())
  end
end
