defmodule SimpleshopThemeWeb.Shop.CheckoutSuccess do
  use SimpleshopThemeWeb, :live_view

  alias SimpleshopTheme.Orders

  @impl true
  def mount(%{"session_id" => session_id}, _session, socket) do
    order = Orders.get_order_by_stripe_session(session_id)

    # Subscribe to order status updates (webhook may arrive after redirect)
    if order && connected?(socket) do
      Phoenix.PubSub.subscribe(SimpleshopTheme.PubSub, "order:#{order.id}:status")
    end

    # Clear the cart after successful checkout
    socket =
      if order && connected?(socket) do
        SimpleshopThemeWeb.CartHook.broadcast_and_update(socket, [])
      else
        socket
      end

    socket =
      socket
      |> assign(:page_title, "Order confirmed")
      |> assign(:order, order)

    {:ok, socket}
  end

  def mount(_params, _session, socket) do
    {:ok, redirect(socket, to: ~p"/")}
  end

  @impl true
  def handle_info({:order_paid, order}, socket) do
    {:noreply, assign(socket, :order, order)}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <SimpleshopThemeWeb.PageTemplates.checkout_success {assigns} />
    """
  end
end
