defmodule WhoNeedHelpWeb.MetricsController do
  use WhoNeedHelpWeb, :controller

  alias WhoNeedHelpWeb.MetricsAccess

  @content_type "text/plain; version=0.0.4"

  # Sobelow's HTML-oriented SendResp check cannot infer this fixed Prometheus
  # text content type. The response is not rendered in an HTML context.
  # sobelow_skip ["XSS.SendResp"]
  def show(conn, _params) do
    token = Application.get_env(:who_need_help, :metrics_token)

    if MetricsAccess.authorized?(get_req_header(conn, "authorization"), token) do
      body = TelemetryMetricsPrometheus.Core.scrape(:prometheus_metrics)

      conn
      |> put_resp_header("cache-control", "no-store")
      |> put_resp_header("x-wnh-node", to_string(node()))
      |> put_resp_content_type(@content_type)
      |> send_resp(:ok, body)
    else
      conn
      |> put_resp_header("cache-control", "no-store")
      |> put_resp_header("www-authenticate", "Bearer")
      |> send_resp(:unauthorized, "Unauthorized\n")
    end
  end
end
