# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.ActivityPub.MRF.ConvertNonDirectToPublic do
  alias Pleroma.Config
  alias Pleroma.User

  @behaviour Pleroma.Web.ActivityPub.MRF.Policy

  require Pleroma.Constants

  @impl true
  def filter(
        %{
          "type" => "Create",
          "to" => to,
          "cc" => cc,
          "actor" => actor,
          "object" => object
        } = message
      ) do
    actor_info = URI.parse(actor)
    user = User.get_cached_by_ap_id(actor)
    instance_domain = Config.get([Pleroma.Web.Endpoint, :url, :host])

    # Determine visibility
    visibility =
      cond do
        Pleroma.Constants.as_public() in to -> "public"
        Pleroma.Constants.as_public() in cc -> "unlisted"
        user.follower_address in to -> "followers"
        true -> "direct"
      end

    if visibility in ["unlisted", "followers"] and actor_info.host != instance_domain do
      to = List.delete(to, user.follower_address) ++ [Pleroma.Constants.as_public()]
      cc = List.delete(cc, Pleroma.Constants.as_public()) ++ [user.follower_address]

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

      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(message), do: {:ok, message}

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