defmodule Front.WorkflowPage.Errors.StructuredError do
  @moduledoc """
    A structured log error is generated by the SPC compiler.

    The format is the following:

    {
      "location": {
        "path": ["blocks", "0", "run", "when"],
        "file": "semaphore.yml"
      },
      "message": "Unprocessable something",
      "type":"ErrorInvalidWhenExpression"
    }
  """

  defstruct [:path, :filename, :message, :type]

  def parsable?(raw_err), do: elem(parse(raw_err), 0) == :ok
  def parse(raw_err), do: Poison.decode(raw_err)

  def path(err) do
    get_in(err, ["location", "path"])
    |> Enum.reduce("", fn el, result ->
      cond do
        result == "" ->
          el

        is_int(el) ->
          result <> "[" <> el <> "]"

        true ->
          result <> " / " <> el
      end
    end)
  end

  def missing_branch?(err) do
    err["type"] == "ErrorChangeInMissingBranch"
  end

  def invalid_when?(err) do
    err["type"] == "ErrorInvalidWhenExpression"
  end

  def initialization_failed?(err) do
    err["type"] == "ErrorInitializationFailed"
  end

  defp is_int(str) do
    str =~ ~r/^[0-9]+$/
  end
end
