Skip to main content

lib/triple/feedback.ex

defmodule Triple.Feedback do
  @moduledoc """
  Report incorrect or missing enrichment data back to Triple, helping its
  models improve over time.
  """

  alias Triple.{Client, Config, Error}
  alias Triple.Types.FeedbackRequest

  @doc """
  Reports an issue with a previously-enriched transaction.

  `attrs` matches `Triple.Types.FeedbackRequest`: `transaction_id`,
  `report`, and `response_value` are required; `feedback` is an optional
  free-text correction suggestion.

  Returns `{:ok, :no_content}` on success (the API replies `204`).

  ## Examples

      Triple.Feedback.report(client, %{
        transaction_id: "txn_123",
        report: :brand_name,
        response_value: "AMZN MKTP UK",
        feedback: "Should be Amazon"
      })
      #=> {:ok, :no_content}
  """
  @spec report(Config.t(), map() | keyword()) :: {:ok, :no_content} | {:error, Error.t()}
  def report(%Config{} = config, attrs) do
    with {:ok, request} <- FeedbackRequest.new(attrs) do
      config
      |> Client.request(:post, "/v1/customer-feedback/",
        json: FeedbackRequest.to_payload(request)
      )
      |> decode()
    end
  end

  @doc "Same as `report/2`, but raises instead of returning `{:error, _}`."
  @spec report!(Config.t(), map() | keyword()) :: :no_content
  def report!(config, attrs) do
    case report(config, attrs) do
      {:ok, result} -> result
      {:error, error} -> raise error
    end
  end

  defp decode({:ok, %Req.Response{}}), do: {:ok, :no_content}
  defp decode({:error, _error} = error), do: error
end