defmodule BerrypodWeb.SearchHook do
  @moduledoc """
  LiveView on_mount hook for product search.

  Mounted in the public_shop live_session to give all shop LiveViews
  search state and shared event handlers via attach_hook.

  Handles these events:
  - `search` - run FTS5 search with debounced query
  - `clear_search` - reset search state
  """

  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [attach_hook: 4]

  alias Berrypod.Search

  def on_mount(:mount_search, _params, _session, socket) do
    socket =
      socket
      |> assign(:search_query, "")
      |> assign(:search_results, [])
      |> assign(:search_open, false)
      |> attach_hook(:search_events, :handle_event, &handle_search_event/3)

    {:cont, socket}
  end

  defp handle_search_event("open_search", _params, socket) do
    {:halt, assign(socket, :search_open, true)}
  end

  defp handle_search_event("search", %{"value" => query}, socket) do
    results = Search.search(query)

    socket =
      socket
      |> assign(:search_query, query)
      |> assign(:search_results, results)

    {:halt, socket}
  end

  defp handle_search_event("clear_search", _params, socket) do
    socket =
      socket
      |> assign(:search_query, "")
      |> assign(:search_results, [])
      |> assign(:search_open, false)

    {:halt, socket}
  end

  defp handle_search_event(_event, _params, socket), do: {:cont, socket}
end
