defmodule ClacksWeb.Plug.HTTPSignature do
  require Logger
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    case get_req_header(conn, "signature") do
      [_signature | _] ->
        conn =
          conn
          |> put_req_header(
            "(request-target)",
            String.downcase(conn.method) <> " " <> conn.request_path
          )
          |> case do
            %Plug.Conn{assigns: %{digest: digest}} = conn when is_binary(digest) ->
              put_req_header(conn, "digest", digest)

            _ ->
              conn
          end

        if HTTPSignatures.validate_conn(conn) do
          conn
        else
          Logger.debug("Could not validate signature for #{inspect(conn)}")

          conn
          |> put_status(401)
          |> halt()
        end

      _ ->
        Logger.debug("No signature header for #{inspect(conn)}")

        conn
        |> put_status(401)
        |> halt()
    end
  end
end