defmodule Mv.OidcRoleSyncConfigTest do
  @moduledoc """
  Tests for OIDC role sync configuration (OIDC_ADMIN_GROUP_NAME, OIDC_GROUPS_CLAIM).
  Reads via Mv.Config (ENV first, then Settings).
  """
  use Mv.DataCase, async: false

  alias Mv.OidcRoleSyncConfig

  describe "oidc_admin_group_name/0" do
    test "returns nil when OIDC_ADMIN_GROUP_NAME is not configured" do
      restore = clear_env("OIDC_ADMIN_GROUP_NAME")
      on_exit(restore)

      assert OidcRoleSyncConfig.oidc_admin_group_name() == nil
    end

    test "returns configured admin group name when set via ENV" do
      restore = set_env("OIDC_ADMIN_GROUP_NAME", "mila-admin")
      on_exit(restore)

      assert OidcRoleSyncConfig.oidc_admin_group_name() == "mila-admin"
    end
  end

  describe "oidc_groups_claim/0" do
    test "returns default \"groups\" when OIDC_GROUPS_CLAIM is not configured" do
      restore = clear_env("OIDC_GROUPS_CLAIM")
      on_exit(restore)

      assert OidcRoleSyncConfig.oidc_groups_claim() == "groups"
    end

    test "returns configured claim name when OIDC_GROUPS_CLAIM is set via ENV" do
      restore = set_env("OIDC_GROUPS_CLAIM", "ak_groups")
      on_exit(restore)

      assert OidcRoleSyncConfig.oidc_groups_claim() == "ak_groups"
    end
  end

  defp set_env(key, value) do
    previous = System.get_env(key)
    System.put_env(key, value)

    fn ->
      if previous, do: System.put_env(key, previous), else: System.delete_env(key)
    end
  end

  defp clear_env(key) do
    previous = System.get_env(key)
    System.delete_env(key)

    fn ->
      if previous, do: System.put_env(key, previous)
    end
  end
end
