defmodule WhoNeedHelpWeb.MetricsControllerTest do
  use WhoNeedHelpWeb.ConnCase, async: false

  test "rejects a request without credentials", %{conn: conn} do
    conn = get(conn, "/metrics")

    assert response(conn, 401) == "Unauthorized\n"
    assert get_resp_header(conn, "www-authenticate") == ["Bearer"]
    assert get_resp_header(conn, "cache-control") == ["no-store"]
  end

  test "rejects an incorrect bearer token", %{conn: conn} do
    conn =
      conn
      |> put_req_header("authorization", "Bearer incorrect-token")
      |> get("/metrics")

    assert response(conn, 401) == "Unauthorized\n"
  end

  test "exports Prometheus metrics for the configured bearer token", %{conn: conn} do
    get(conn, "/healthz/live")
    WhoNeedHelp.Repo.query!("SELECT 1")

    conn =
      conn
      |> put_req_header("authorization", "Bearer test-metrics-token")
      |> get("/metrics")

    body = response(conn, 200)

    assert get_resp_header(conn, "content-type") == [
             "text/plain; version=0.0.4; charset=utf-8"
           ]

    assert get_resp_header(conn, "cache-control") == ["no-store"]
    assert get_resp_header(conn, "x-wnh-node") == [to_string(node())]
    assert body =~ "# TYPE who_need_help_http_requests_total counter"
    assert body =~ "who_need_help_http_requests_total "
    assert body =~ "who_need_help_http_request_duration_microseconds_total "
    assert body =~ "who_need_help_database_query_execution_duration_microseconds_total "
    assert body =~ "who_need_help_database_query_queue_duration_microseconds_total "
    assert body =~ "who_need_help_database_query_decode_duration_microseconds_total "
  end
end
