defmodule WhoNeedHelpWeb.E2eFailureController do
  @moduledoc false

  use WhoNeedHelpWeb, :controller

  @confirmation "crash-exact-e2e-node"

  def crash_node(conn, %{"confirmation" => @confirmation, "node" => target}) do
    current_nodes = [Node.self() | Node.list()]

    case Enum.find(current_nodes, &(to_string(&1) == target)) do
      nil ->
        conn
        |> put_status(:not_found)
        |> json(%{error: "unknown_node"})

      target_node ->
        true = :rpc.cast(target_node, :timer, :apply_after, [500, :erlang, :halt, [1]])

        conn
        |> put_status(:accepted)
        |> json(%{status: "scheduled", node: target})
    end
  end

  def crash_node(conn, _params) do
    conn
    |> put_status(:unprocessable_entity)
    |> json(%{error: "invalid_confirmation"})
  end
end
