defmodule BerrypodWeb.RTest do
  use Berrypod.DataCase, async: false

  alias BerrypodWeb.R
  alias Berrypod.Pages

  setup do
    # Clear caches between tests
    R.invalidate_all_sync()
    Berrypod.Pages.PageCache.invalidate_all()
    :ok
  end

  describe "page path functions" do
    test "returns default paths when no custom slugs set" do
      assert R.cart() == "/cart"
      assert R.about() == "/about"
      assert R.contact() == "/contact"
      assert R.search() == "/search"
    end

    test "returns custom path after url_slug is set" do
      {:ok, _} = Pages.update_page_url_slug("cart", "basket")

      assert R.cart() == "/basket"
    end

    test "returns default path after url_slug is cleared" do
      {:ok, _} = Pages.update_page_url_slug("about", "our-story")
      assert R.about() == "/our-story"

      {:ok, _} = Pages.update_page_url_slug("about", "")
      assert R.about() == "/about"
    end
  end

  describe "page/1 generic function" do
    test "routes through specific functions for system pages" do
      {:ok, _} = Pages.update_page_url_slug("cart", "basket")

      assert R.page("cart") == "/basket"
      assert R.page("home") == "/"
    end

    test "returns /slug for custom pages" do
      assert R.page("my-custom-page") == "/my-custom-page"
    end
  end

  describe "reverse lookups" do
    test "page_type_from_slug finds system page by custom url" do
      {:ok, _} = Pages.update_page_url_slug("about", "our-story")

      assert R.page_type_from_slug("our-story") == {:page, :about}
    end

    test "page_type_from_slug finds system page by default url" do
      assert R.page_type_from_slug("cart") == {:page, :cart}
      assert R.page_type_from_slug("about") == {:page, :about}
    end

    test "page_type_from_slug returns nil for unknown slug" do
      assert R.page_type_from_slug("nonexistent") == nil
    end

    test "page_type_from_slug finds custom page" do
      {:ok, _} = Pages.create_custom_page(%{slug: "faq", title: "FAQ", published: true})

      assert {:custom, page} = R.page_type_from_slug("faq")
      assert page.slug == "faq"
    end
  end

  describe "prefix functions" do
    test "returns default prefixes" do
      assert R.product(123) == "/products/123"
      assert R.collection("art") == "/collections/art"
      assert R.order("ORD-123") == "/orders/ORD-123"
    end
  end

  describe "url/1" do
    test "prepends endpoint URL to path" do
      url = R.url("/cart")
      assert String.starts_with?(url, "http")
      assert String.ends_with?(url, "/cart")
    end
  end
end
