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

  alias Berrypod.{Analytics, Orders, Pages}

  @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(Berrypod.PubSub, "order:#{order.id}:status")
    end

    # Track purchase event
    if order && connected?(socket) && socket.assigns[:analytics_visitor_hash] do
      attrs =
        BerrypodWeb.AnalyticsHook.attrs(socket)
        |> Map.merge(%{pathname: "/checkout/success", revenue: order.total})

      Analytics.track_event("purchase", attrs)
    end

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

    page = Pages.get_page("checkout_success")

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

    {: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"""
    <BerrypodWeb.PageRenderer.render_page {assigns} />
    """
  end
end
