defmodule Pleroma.Web.ActivityPub.MRF.ExNihiloNihilFit do
  @behaviour Pleroma.Web.ActivityPub.MRF.Policy

  require Pleroma.Constants

  defp check_avatar_rewrite(actor, object) do
    actor_info = URI.parse(actor)

    cond do
      actor_info.host in ["youjo.love", "lolison.top", "lolison.network", "rapemeat.solutions", "ghetti.monster", "nnia.space", "freak.university", "rot.gives"] ->
        {:ok, Map.put(object, "icon", %{"type" => "Image", "url" => "https://ryona.agency/media/ca97357084c09219ce06457594af4a2054a97f5b52b4dde424aacdd988dc59a5.png"})}

      actor in ["https://poa.st/users/graf", "https://khajiit.tech/users/graf"] ->
        {:ok, Map.put(object, "icon", %{"type" => "Image", "url" => "https://ryona.agency/media/3a49fe5681e1311b5cf9c0c81b698c090321a59605baa2a09fff818237970b8d.png"})}

      true ->
        {:ok, object}
    end
  end

  @impl true
  def filter(
        %{
          "type" => "Create",
          "to" => to,
          "cc" => cc,
          "object" => object
        } = message
      ) do

    if(Enum.member?(to++cc, "https://ryona.agency/users/mint") && (Enum.member?(to++cc, "https://freespeechextremist.com/users/Heliodramus") or Enum.member?(to++cc, "https://freespeechextremist.com/users/DiamondMind"))) do
      to = List.delete(to, "https://ryona.agency/users/mint")
      cc = List.delete(cc, "https://ryona.agency/users/mint")
      tag = List.delete(object["tag"], Enum.find(object["tag"], fn map -> map["href"] == "https://ryona.agency/users/mint" end))

      object =
        object
        |> Map.put("to", to)
        |> Map.put("cc", cc)
        |> Map.put("tag", tag)

      message =
        message
        |> Map.put("to", to)
        |> Map.put("cc", cc)
        |> Map.put("object", object)

      {:ok, message}
    else
      {:ok, message}
    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_avatar_rewrite(actor, object) do
      {:ok, object}
    end
  end

  @impl true
  def filter(object) do
    {:ok, object}
  end

  @impl true
  def describe, do: {:ok, %{}}
end
