defmodule MvWeb.MembershipFeeTypeLive.IndexTest do
  @moduledoc """
  Tests for membership fee types list view.
  """
  use MvWeb.ConnCase, async: false

  import Phoenix.LiveViewTest

  alias Mv.MembershipFees.MembershipFeeType

  require Ash.Query

  # Use global setup from ConnCase which provides admin user with role
  # No custom setup needed

  # Helper to create a membership fee type
  # Uses admin_user to test permissions (UI-/Permissions-nah)
  defp create_fee_type(attrs, admin_user) do
    default_attrs = %{
      name: "Test Fee Type #{System.unique_integer([:positive])}",
      amount: Decimal.new("50.00"),
      interval: :yearly
    }

    attrs = Map.merge(default_attrs, attrs)

    MembershipFeeType
    |> Ash.Changeset.for_create(:create, attrs)
    |> Ash.create!(actor: admin_user)
  end

  # Helper to create a member. Requires actor (e.g. admin_user from setup); no fallback so
  # missing-actor bugs are not masked in tests.
  defp create_member(attrs, actor) do
    default_attrs = %{
      first_name: "Test",
      last_name: "Member",
      email: "test.member.#{System.unique_integer([:positive])}@example.com"
    }

    attrs = Map.merge(default_attrs, attrs)
    {:ok, member} = Mv.Membership.create_member(attrs, actor: actor)
    member
  end

  describe "list display" do
    test "displays all membership fee types with correct data", %{
      conn: conn,
      current_user: admin_user
    } do
      _fee_type1 =
        create_fee_type(
          %{name: "Regular", amount: Decimal.new("60.00"), interval: :yearly},
          admin_user
        )

      _fee_type2 =
        create_fee_type(
          %{name: "Reduced", amount: Decimal.new("30.00"), interval: :yearly},
          admin_user
        )

      {:ok, _view, html} = live(conn, "/membership_fee_types")

      assert html =~ "Regular"
      assert html =~ "Reduced"
      assert html =~ "60" || html =~ "60,00"
      assert html =~ "30" || html =~ "30,00"
      assert html =~ "Yearly" || html =~ "Jährlich"
    end

    test "member count column shows correct count", %{conn: conn, current_user: admin_user} do
      fee_type = create_fee_type(%{interval: :yearly}, admin_user)

      # Create 3 members with this fee type
      Enum.each(1..3, fn _ ->
        create_member(%{membership_fee_type_id: fee_type.id}, admin_user)
      end)

      {:ok, _view, html} = live(conn, "/membership_fee_types")

      assert html =~ "3" || html =~ "Members" || html =~ "Mitglieder"
    end

    test "create button navigates to form", %{conn: conn} do
      {:ok, view, _html} = live(conn, "/membership_fee_types")

      {:error, {:live_redirect, %{to: to}}} =
        view
        |> element("a[href='/membership_fee_types/new']")
        |> render_click()

      assert to == "/membership_fee_types/new"
    end

    test "edit button per row navigates to edit form", %{conn: conn, current_user: admin_user} do
      fee_type = create_fee_type(%{interval: :yearly}, admin_user)

      {:ok, view, _html} = live(conn, "/membership_fee_types")

      {:error, {:live_redirect, %{to: to}}} =
        view
        |> element("a[href='/membership_fee_types/#{fee_type.id}/edit']")
        |> render_click()

      assert to == "/membership_fee_types/#{fee_type.id}/edit"
    end
  end

  describe "delete functionality" do
    test "delete button disabled if type is in use", %{conn: conn, current_user: admin_user} do
      fee_type = create_fee_type(%{interval: :yearly}, admin_user)
      create_member(%{membership_fee_type_id: fee_type.id}, admin_user)

      {:ok, _view, html} = live(conn, "/membership_fee_types")

      # Delete button should be disabled
      assert html =~ "disabled" || html =~ "cursor-not-allowed"
    end

    test "delete button works if type is not in use", %{conn: conn, current_user: admin_user} do
      fee_type = create_fee_type(%{interval: :yearly}, admin_user)
      # No members assigned

      {:ok, view, _html} = live(conn, "/membership_fee_types")

      # Delete button should be enabled
      view
      |> element("button[phx-click='delete'][phx-value-id='#{fee_type.id}']")
      |> render_click()

      # Type should be deleted - use admin_user to test permissions
      assert {:error, %Ash.Error.Invalid{errors: [%Ash.Error.Query.NotFound{}]}} =
               Ash.get(MembershipFeeType, fee_type.id,
                 domain: Mv.MembershipFees,
                 actor: admin_user
               )
    end
  end

  describe "permissions" do
    test "only admin can access", %{conn: conn} do
      # This test assumes non-admin users cannot access
      # Adjust based on actual permission implementation
      {:ok, _view, html} = live(conn, "/membership_fee_types")

      # Should show the page (admin user in setup)
      assert html =~ "Membership Fee Types" || html =~ "Beitragsarten"
    end
  end
end
