defmodule BerrypodWeb.Plugs.RedirectsTest do
  use BerrypodWeb.ConnCase, async: true

  alias Berrypod.Redirects

  setup do
    Redirects.create_table()
    :ok
  end

  describe "trailing slash normalisation" do
    test "strips trailing slash and redirects", %{conn: conn} do
      conn = get(conn, "/products/foo/")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/foo"]
    end

    test "preserves query params on trailing slash redirect", %{conn: conn} do
      conn = get(conn, "/products/foo/?Color=Sand&Size=S")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/foo?Color=Sand&Size=S"]
    end

    test "does not strip trailing slash from root path", %{conn: conn} do
      conn = get(conn, "/")

      # Should not redirect — just pass through to the app
      refute conn.status == 301
    end
  end

  describe "case normalisation" do
    test "lowercases path and redirects", %{conn: conn} do
      conn = get(conn, "/Products/Foo")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/foo"]
    end

    test "preserves query param casing", %{conn: conn} do
      conn = get(conn, "/Products/Foo?Color=Sand")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/foo?Color=Sand"]
    end

    test "does not redirect already-lowercase paths", %{conn: conn} do
      # This will get a 404 or 200 from the app, not a 301
      conn = get(conn, "/products/nonexistent-lowercase-path")

      refute conn.status == 301
    end
  end

  describe "custom redirects" do
    test "redirects matching path with 301", %{conn: conn} do
      {:ok, _} =
        Redirects.create_auto(%{
          from_path: "/products/old-tee",
          to_path: "/products/new-tee",
          source: "auto_slug_change"
        })

      conn = get(conn, "/products/old-tee")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/new-tee"]
    end

    test "preserves query string on custom redirect", %{conn: conn} do
      {:ok, _} =
        Redirects.create_auto(%{
          from_path: "/products/old-hoodie",
          to_path: "/products/new-hoodie",
          source: "auto_slug_change"
        })

      conn = get(conn, "/products/old-hoodie?Color=Sand&Size=S")

      assert conn.status == 301
      assert get_resp_header(conn, "location") == ["/products/new-hoodie?Color=Sand&Size=S"]
    end

    test "passes through when no redirect exists", %{conn: conn} do
      conn = get(conn, "/products/no-redirect-here")

      refute conn.status == 301
    end
  end
end
