defmodule Aprsme.PromExTest do
  use ExUnit.Case, async: true

  alias PromEx.Plugins.Phoenix

  describe "plugins/0" do
    setup do
      {:ok, plugins: Aprsme.PromEx.plugins()}
    end

    test "includes the built-in PromEx plugins", %{plugins: plugins} do
      modules = plugin_modules(plugins)

      assert PromEx.Plugins.Application in modules
      assert PromEx.Plugins.Beam in modules
      assert Phoenix in modules
      assert PromEx.Plugins.PhoenixLiveView in modules
      assert PromEx.Plugins.Ecto in modules
    end

    test "includes the custom Aprsme plugin", %{plugins: plugins} do
      assert Aprsme.PromEx.Plugins.Aprsme in plugin_modules(plugins)
    end

    test "phoenix plugin is configured with router and endpoint", %{plugins: plugins} do
      {_module, opts} =
        Enum.find(plugins, fn
          {Phoenix, _opts} -> true
          _ -> false
        end)

      assert opts[:router] == AprsmeWeb.Router
      assert opts[:endpoint] == AprsmeWeb.Endpoint
      assert AprsmeWeb.Router.__info__(:functions) != []
    end

    test "ecto plugin is configured with the app's repo", %{plugins: plugins} do
      {_module, opts} =
        Enum.find(plugins, fn
          {PromEx.Plugins.Ecto, _opts} -> true
          _ -> false
        end)

      assert opts[:otp_app] == :aprsme
      assert opts[:repos] == [Aprsme.Repo]
      assert {:module, _} = Code.ensure_loaded(Aprsme.Repo)
      assert Aprsme.Repo.__info__(:functions) != []
    end
  end

  describe "dashboard_assigns/0" do
    test "returns the configured datasource and interval" do
      assigns = Aprsme.PromEx.dashboard_assigns()
      assert Keyword.get(assigns, :datasource_id) == "Prometheus"
      assert Keyword.get(assigns, :default_selected_interval) == "30s"
    end
  end

  describe "dashboards/0" do
    test "returns an empty list (dashboards provisioned externally via Grafana)" do
      assert Aprsme.PromEx.dashboards() == []
    end
  end

  defp plugin_modules(plugins) do
    Enum.map(plugins, fn
      {mod, _opts} -> mod
      mod when is_atom(mod) -> mod
    end)
  end
end
