defmodule Pleroma.Web.ActivityPub.MRF.MediaRemovalPerActor do
  @moduledoc "Removes media per actor (replaces TagPolicy due to its lack of transparency)"
  @behaviour Pleroma.Web.ActivityPub.MRF.Policy

  defp check_profile_media_removal(actor, object) do
    if Enum.member?(Pleroma.Config.get([:mrf_media_removal_per_actor, :actors]), actor) do
      {:ok, Map.delete(Map.delete(object, "icon"), "image")}
    else
      {:ok, object}
    end
  end

  defp check_media_removal(actor, object) do
    if Enum.member?(Pleroma.Config.get([:mrf_media_removal_per_actor, :actors]), actor) do
      {:ok, Map.delete(object, "attachment")}
    else
      {:ok, object}
    end
  end

  @impl true
  def filter(%{"id" => actor, "type" => obj_type} = object)
      when obj_type in ["Application", "Group", "Organization", "Person", "Service"] do
    with {:ok, object} <- check_profile_media_removal(actor, object) do
      {:ok, object}
    end
  end

  @impl true
  def filter(%{"actor" => actor} = object) do
    with {:ok, object} <- check_media_removal(actor, object) do
      {:ok, object}
    end
  end

  @impl true
  def describe do
    {:ok,
      %{mrf_media_removal_per_actor:
        %{actors: Pleroma.Config.get([:mrf_media_removal_per_actor, :actors])}
      }
    }
  end

  @impl true
  def config_description do
    %{
      key: :mrf_media_removal_per_actor,
      related_policy: "Pleroma.Web.ActivityPub.MRF.MediaRemovalPerActor",
      description: "Removes media per actor",
      children: [
        %{
          key: :actors,
          type: {:list, :string},
          label: "List of affected actors",
          suggestions: ["https://instance.tld/users/pedophile"]
        }
      ]
    }
  end
end
