defmodule BerrypodWeb.Shop.Pages.CheckoutSuccess do
  @moduledoc """
  Checkout success page handler for the unified Shop.Page LiveView.
  Handles PubSub subscription for order status updates.
  """

  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [connected?: 1, redirect: 2]

  alias Berrypod.{Analytics, Orders, Pages}
  alias BerrypodWeb.R

  def init(socket, %{"session_id" => session_id}, _uri) 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: R.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

    # Track subscription for cleanup when leaving this page
    socket =
      if order do
        assign(socket, :checkout_order_subscription, "order:#{order.id}:status")
      else
        socket
      end

    page = Pages.get_page("checkout_success")

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

    {:noreply, socket}
  end

  def init(socket, _params, _uri) do
    {:redirect, redirect(socket, to: R.home())}
  end

  def handle_params(_params, _uri, socket) do
    {:noreply, socket}
  end

  def handle_event(_event, _params, _socket), do: :cont

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

  def handle_info(_msg, _socket), do: :cont

  # Called when leaving this page to clean up subscription
  def cleanup(socket) do
    if topic = socket.assigns[:checkout_order_subscription] do
      Phoenix.PubSub.unsubscribe(Berrypod.PubSub, topic)
    end

    socket
    |> assign(:checkout_order_subscription, nil)
    |> assign(:order, nil)
  end
end
