defmodule Mv.Membership.SettingTest do
  use Mv.DataCase, async: false
  alias Mv.Membership

  describe "Settings Resource" do
    test "can read settings" do
      # Settings should be a singleton resource
      assert {:ok, _settings} = Membership.get_settings()
    end

    test "settings have club_name attribute" do
      {:ok, settings} = Membership.get_settings()
      assert Map.has_key?(settings, :club_name)
    end

    test "can update club_name" do
      {:ok, settings} = Membership.get_settings()

      assert {:ok, updated_settings} =
               Membership.update_settings(settings, %{club_name: "New Club Name"})

      assert updated_settings.club_name == "New Club Name"
    end

    test "club_name is required" do
      {:ok, settings} = Membership.get_settings()

      assert {:error, %Ash.Error.Invalid{errors: errors}} =
               Membership.update_settings(settings, %{club_name: nil})

      assert error_message(errors, :club_name) =~ "must be present"
    end

    test "club_name cannot be empty" do
      {:ok, settings} = Membership.get_settings()

      assert {:error, %Ash.Error.Invalid{errors: errors}} =
               Membership.update_settings(settings, %{club_name: ""})

      assert error_message(errors, :club_name) =~ "must be present"
    end
  end

  # Helper function to extract error messages
  defp error_message(errors, field) do
    errors
    |> Enum.filter(fn err -> Map.get(err, :field) == field end)
    |> Enum.map(&Map.get(&1, :message, ""))
    |> List.first() || ""
  end
end
