defmodule MvWeb.StatisticsLiveTest do
  @moduledoc """
  Tests for the Statistics LiveView at /statistics.

  Uses explicit auth: conn is authenticated with a role that has access to
  the statistics page (read_only by default; override with @tag :role).
  """
  use MvWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  alias Mv.MembershipFees.MembershipFeeType

  describe "statistics page" do
    @describetag role: :read_only
    test "renders statistics page with title and key labels for authenticated user with access",
         %{
           conn: conn
         } do
      {:ok, _view, html} = live(conn, ~p"/statistics")

      assert html =~ "Statistics"
      assert html =~ "Active members"
      assert html =~ "Unpaid"
      assert html =~ "Contributions by year"
      assert html =~ "Member numbers by year"
    end

    test "page shows overview of all relevant years without year selector", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/statistics")

      # No year dropdown: single select for year should not be present as main control
      assert html =~ "Overview" or html =~ "overview"
      # table header or legend
      assert html =~ "Year"
    end

    test "fee_type_id in URL updates selected filter and contributions", %{conn: conn} do
      actor = Mv.Helpers.SystemActor.get_system_actor()

      fee_types =
        MembershipFeeType
        |> Ash.Query.sort(name: :asc)
        |> Ash.read!(domain: Mv.MembershipFees, actor: actor)

      fee_type =
        case List.first(fee_types) do
          nil ->
            MembershipFeeType
            |> Ash.Changeset.for_create(:create, %{
              name: "Test Fee #{System.unique_integer([:positive])}",
              amount: Decimal.new("50.00"),
              interval: :yearly
            })
            |> Ash.create!(actor: actor)

          ft ->
            ft
        end

      path = ~p"/statistics" <> "?" <> URI.encode_query(%{"fee_type_id" => fee_type.id})
      {:ok, view, html} = live(conn, path)

      assert view |> element("select#fee-type-filter") |> has_element?()
      assert html =~ fee_type.name
      assert html =~ "Contributions by year"
    end
  end

  describe "statistics page with own_data role" do
    @describetag role: :member
    test "redirects when user has only own_data (no access to statistics page)", %{conn: conn} do
      # member role uses own_data permission set; /statistics is not in own_data pages
      conn = get(conn, ~p"/statistics")
      assert redirected_to(conn) != ~p"/statistics"
    end
  end
end
