defmodule MvWeb.MemberLive.IndexGroupsSortingTest do
  @moduledoc """
  Tests for sorting by groups in the member overview.
  """
  # async: false to prevent PostgreSQL deadlocks when creating members and groups
  use MvWeb.ConnCase, async: false
  import Phoenix.LiveViewTest
  require Ash.Query

  alias Mv.Membership.{Group, MemberGroup}

  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"},
        actor: system_actor
      )

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

    {:ok, member4} =
      Mv.Membership.create_member(
        %{first_name: "David", last_name: "Davis", email: "david@example.com"},
        actor: system_actor
      )

    {:ok, group_a} =
      Group
      |> Ash.Changeset.for_create(:create, %{name: "A Group"})
      |> Ash.create(actor: system_actor)

    {:ok, group_b} =
      Group
      |> Ash.Changeset.for_create(:create, %{name: "B Group"})
      |> Ash.create(actor: system_actor)

    {:ok, _mg1} =
      MemberGroup
      |> Ash.Changeset.for_create(:create, %{member_id: member1.id, group_id: group_a.id})
      |> Ash.create(actor: system_actor)

    {:ok, _mg2} =
      MemberGroup
      |> Ash.Changeset.for_create(:create, %{member_id: member2.id, group_id: group_b.id})
      |> Ash.create(actor: system_actor)

    %{member1: member1, member2: member2, member4: member4, group_a: group_a, group_b: group_b}
  end

  test "sorts by group name ascending", %{conn: conn, group_a: group_a} do
    conn = conn_with_oidc_user(conn)
    {:ok, view, _html} = live(conn, "/members")

    view
    |> element("[data-testid='groups']")
    |> render_click()

    # Sort was applied: button shows ascending state and group names still visible
    assert has_element?(view, "[data-testid='groups']")
    html = render(view)
    assert html =~ group_a.name
  end
end
