defmodule BerrypodWeb.Shop.SearchPageTest do
  use BerrypodWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  alias Berrypod.ProductsFixtures

  setup do
    user_fixture()
    {:ok, _} = Berrypod.Settings.set_site_live(true)
    :ok
  end

  describe "GET /search" do
    test "renders search page with empty query", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/search")

      assert html =~ "Search"
      assert html =~ ~s(placeholder="Search products...")
    end

    test "renders search results for a matching query", %{conn: conn} do
      product =
        ProductsFixtures.complete_product_fixture(%{title: "Blue Mountain Print"})

      Berrypod.Search.index_product(product)

      {:ok, _view, html} = live(conn, ~p"/search?q=mountain")

      assert html =~ "Blue Mountain Print"
      assert html =~ "1 result"
    end

    test "renders no-results message for unmatched query", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/search?q=nonexistent")

      assert html =~ "No products found"
    end

    test "search form submits via LiveView and updates URL", %{conn: conn} do
      product =
        ProductsFixtures.complete_product_fixture(%{title: "Red Sunset Poster"})

      Berrypod.Search.index_product(product)

      {:ok, view, _html} = live(conn, ~p"/search")

      html =
        view
        |> form(".search-page-form", %{"q" => "sunset"})
        |> render_submit()

      assert html =~ "Red Sunset Poster"
    end
  end
end
