defmodule ToweropsWeb.TelemetryTest do
  use ExUnit.Case, async: false

  alias ToweropsWeb.Telemetry

  describe "metrics/0" do
    test "returns list of telemetry metrics" do
      metrics = Telemetry.metrics()

      assert is_list(metrics)
      refute metrics == []

      # Verify Phoenix metrics exist
      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:phoenix, :endpoint, :stop]
             end)

      # Verify Database metrics exist
      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:towerops, :repo, :query, :total_time]
             end)

      # Verify VM metrics exist
      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:vm, :memory, :total]
             end)

      # Verify Exq metrics exist
      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:towerops, :exq, :queue, :size]
             end)

      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:towerops, :exq, :processes, :busy]
             end)

      # Verify Redis metrics exist
      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:towerops, :redis, :connected_clients]
             end)

      assert Enum.any?(metrics, fn metric ->
               metric.event_name == [:towerops, :redis, :used_memory]
             end)
    end
  end

  describe "parse_redis_info/1" do
    test "parses Redis INFO output correctly" do
      info_string = """
      # Server
      redis_version:7.0.0
      # Stats
      total_commands_processed:1000
      # Memory
      used_memory:1048576
      # Clients
      connected_clients:5
      """

      result = Telemetry.parse_redis_info(info_string)

      assert result["redis_version"] == "7.0.0"
      assert result["total_commands_processed"] == "1000"
      assert result["used_memory"] == "1048576"
      assert result["connected_clients"] == "5"
    end

    test "ignores comment lines" do
      info_string = """
      # Server
      redis_version:7.0.0
      """

      result = Telemetry.parse_redis_info(info_string)

      refute Map.has_key?(result, "# Server")
      assert result["redis_version"] == "7.0.0"
    end

    test "handles empty lines" do
      info_string = """
      redis_version:7.0.0

      total_commands:100
      """

      result = Telemetry.parse_redis_info(info_string)

      assert result["redis_version"] == "7.0.0"
      assert result["total_commands"] == "100"
      assert map_size(result) == 2
    end
  end

  describe "publish_exq_stats/0" do
    test "does not crash in test environment" do
      # In test env, this should not execute but should not crash
      assert :ok = Telemetry.publish_exq_stats()
    end
  end

  describe "publish_redis_stats/0" do
    test "does not crash in test environment" do
      # In test env, this should not execute but should not crash
      assert :ok = Telemetry.publish_redis_stats()
    end
  end
end
