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

  describe "Settings with environment variable" do
    test "club_name can be set via ASSOCIATION_NAME environment variable" do
      # Set environment variable
      System.put_env("ASSOCIATION_NAME", "Test Association from Env")

      try do
        # Get settings - should use environment variable if no DB value exists
        {:ok, settings} = Membership.get_settings()

        # If settings don't have a club_name in DB, it should use the env var
        # This depends on implementation - we'll check that the env var is respected
        assert settings.club_name != nil
      after
        # Clean up
        System.delete_env("ASSOCIATION_NAME")
      end
    end

    test "database value takes precedence over environment variable" do
      # Set environment variable
      System.put_env("ASSOCIATION_NAME", "Env Value")

      try do
        # Set a value in the database
        {:ok, settings} = Membership.get_settings()
        {:ok, _updated} = Membership.update_settings(settings, %{club_name: "DB Value"})

        # Get settings again - should use DB value, not env var
        {:ok, settings_after} = Membership.get_settings()
        assert settings_after.club_name == "DB Value"
      after
        # Clean up
        System.delete_env("ASSOCIATION_NAME")
      end
    end

    test "uses environment variable when database value is not set" do
      # Set environment variable
      System.put_env("ASSOCIATION_NAME", "Default from Env")

      try do
        # Clear database value (if possible) or check that env var is used
        {:ok, settings} = Membership.get_settings()

        # If club_name is nil or empty in DB, should use env var
        # This test depends on implementation details
        # We're testing that the env var fallback works
        club_name = settings.club_name || System.get_env("ASSOCIATION_NAME")
        assert club_name != nil
        assert club_name != ""
      after
        # Clean up
        System.delete_env("ASSOCIATION_NAME")
      end
    end
  end
end
