defmodule WhoNeedHelpWeb.WorkerMetricsPlugTest do
  use WhoNeedHelp.DataCase, async: false

  import Plug.Conn
  import Plug.Test

  alias WhoNeedHelpWeb.WorkerMetricsPlug

  test "liveness and readiness are available without exposing metrics" do
    live = WorkerMetricsPlug.call(conn(:get, "/healthz/live"), [])
    ready = WorkerMetricsPlug.call(conn(:get, "/healthz/ready"), [])

    assert live.status == 200
    assert ready.status == 200
    assert Jason.decode!(live.resp_body)["role"] == "worker"
    assert Jason.decode!(ready.resp_body)["status"] == "ready"
  end

  test "metrics require the independent bearer token" do
    unauthorized = WorkerMetricsPlug.call(conn(:get, "/metrics"), [])

    authorized =
      conn(:get, "/metrics")
      |> put_req_header("authorization", "Bearer test-metrics-token")
      |> WorkerMetricsPlug.call([])

    assert unauthorized.status == 401
    assert get_resp_header(unauthorized, "www-authenticate") == ["Bearer"]
    assert authorized.status == 200
    assert authorized.resp_body =~ "who_need_help_database_query_duration_seconds"
  end

  test "all other methods and paths are unavailable" do
    assert WorkerMetricsPlug.call(conn(:post, "/metrics"), []).status == 404
    assert WorkerMetricsPlug.call(conn(:get, "/"), []).status == 404
  end
end
