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

  import Berrypod.AccountsFixtures

  alias Berrypod.{Redirects, Settings}

  setup do
    Redirects.create_table()
    # Create admin user so SetupHook allows access
    user_fixture()
    # Mark site as live so requests aren't redirected to /coming-soon
    {:ok, _} = Settings.set_site_live(true)
    :ok
  end

  test "records broken URL on 404", %{conn: conn} do
    # Multi-segment path goes through the catch-all route and raises NotFoundError.
    # The BrokenUrlTracker plug catches this and records it before re-raising.
    assert_error_sent :not_found, fn ->
      get(conn, "/zz/nonexistent-path")
    end

    [broken_url] = Redirects.list_broken_urls()
    assert broken_url.path == "/zz/nonexistent-path"
    assert broken_url.recent_404_count == 1
  end

  test "skips static asset paths", %{conn: conn} do
    # Static asset paths should not be recorded as broken URLs.
    # These raise NotFoundError but the tracker ignores them.
    assert_error_sent :not_found, fn ->
      get(conn, "/assets/missing-file.js")
    end

    assert Redirects.list_broken_urls() == []
  end
end
