defmodule ZoeyscomputerWeb.Plugs.ApiAuthentication do
  alias Zoeyscomputer.ApiKeys
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    case get_auth_token(conn) do
      nil ->
        handle_unauthorized(conn)

      token ->
        case ApiKeys.authenticate_api_key(token) do
          nil ->
            handle_unauthorized(conn)

          user ->
            conn
            |> assign(:current_user, user)
            |> assign(:authenticated_with_api_key, true)
        end
    end
  end

  defp get_auth_token(conn) do
    case get_req_header(conn, "authorization") do
      ["Bearer " <> token] -> token
      _ -> nil
    end
  end

  defp handle_unauthorized(conn) do
    conn
    |> put_status(:unauthorized)
    |> Phoenix.Controller.put_view(ZoeyscomputerWeb.ErrorJSON)
    |> Phoenix.Controller.render(:"401")
    |> halt()
  end
end
