defmodule MvWeb.MemberLive.IndexMemberFieldsDisplayTest do
  use MvWeb.ConnCase, async: true
  import Phoenix.LiveViewTest
  require Ash.Query

  setup do
    system_actor = Mv.Helpers.SystemActor.get_system_actor()

    {:ok, member1} =
      Mv.Membership.create_member(
        %{
          first_name: "Alice",
          last_name: "Anderson",
          email: "alice@example.com",
          street: "Main Street",
          house_number: "123",
          postal_code: "12345",
          city: "Berlin",
          country: "Germany",
          join_date: ~D[2020-01-15]
        },
        actor: system_actor
      )

    {:ok, member2} =
      Mv.Membership.create_member(
        %{first_name: "Bob", last_name: "Brown", email: "bob@example.com"},
        actor: system_actor
      )

    %{
      member1: member1,
      member2: member2
    }
  end

  test "shows multiple members correctly", %{conn: conn, member1: m1, member2: m2} do
    conn = conn_with_oidc_user(conn)
    {:ok, _view, html} = live(conn, "/members")

    for m <- [m1, m2], field <- [m.first_name, m.last_name, m.email] do
      assert html =~ field
    end
  end

  test "respects show_in_overview config", %{conn: conn, member1: m} do
    {:ok, settings} = Mv.Membership.get_settings()
    fields_to_hide = [:street, :house_number]

    {:ok, _} =
      Mv.Membership.update_settings(settings, %{
        member_field_visibility: Map.new(fields_to_hide, &{Atom.to_string(&1), false})
      })

    conn = conn_with_oidc_user(conn)
    # Use search query to filter to only the expected member (Alice)
    # This significantly improves test performance by avoiding loading all members from other tests
    {:ok, _view, html} = live(conn, "/members?query=Alice")

    assert html =~ "Email"
    assert html =~ m.email
    refute html =~ m.street
  end
end
