defmodule WhoNeedHelp.ContentRemoval.Notifier do
  import Swoosh.Email

  alias WhoNeedHelp.ContentRemoval.Notice
  alias WhoNeedHelp.Mailer

  def deliver_received(%Notice{contact_email: email} = notice, status_url)
      when is_binary(email) and email != "" do
    deliver(
      email,
      "Who Need Help removal notice #{notice.reference}",
      """
      We received removal notice #{notice.reference}.

      Status: #{notice.status}

      View the current status:
      #{status_url}

      Do not reply with or upload intimate visual material. If someone is in immediate danger,
      contact the emergency service for their location.
      """
    )
  end

  def deliver_received(%Notice{}, _status_url), do: {:ok, :no_contact_email}

  def deliver_decision(%Notice{contact_email: email} = notice, status_url)
      when is_binary(email) and email != "" do
    deliver(
      email,
      "Who Need Help removal notice update #{notice.reference}",
      """
      Removal notice #{notice.reference} was updated.

      Status: #{notice.status}
      Decision or request for information:
      #{notice.resolution_note || "No additional response was provided."}

      View the current status:
      #{status_url}
      """
    )
  end

  def deliver_decision(%Notice{}, _status_url), do: {:ok, :no_contact_email}

  def deliver_operator_alert(%Notice{} = notice) do
    case Application.get_env(:who_need_help, :support_inbox_address) do
      address when is_binary(address) and address != "" ->
        urgency = if notice.status == :urgent_review, do: "URGENT: ", else: ""

        deliver(
          address,
          "#{urgency}New removal notice #{notice.reference}",
          """
          A new #{notice.regime} content-removal notice is waiting for review.

          Reference: #{notice.reference}
          Category: #{notice.category}
          Review due: #{notice.response_due_at || "no statutory deadline recorded"}
          Operator queue: #{WhoNeedHelpWeb.Endpoint.url()}/support/operations

          Do not request the submitter to email or upload intimate visual material.
          """
        )

      _other ->
        {:ok, :not_configured}
    end
  end

  defp deliver(recipient, subject, body) do
    from = Application.fetch_env!(:who_need_help, :mailer_from)

    new()
    |> to(recipient)
    |> from({from[:name], from[:address]})
    |> maybe_reply_to()
    |> subject(subject)
    |> text_body(body)
    |> Mailer.deliver()
  end

  defp maybe_reply_to(email) do
    case Application.get_env(:who_need_help, :support_inbox_address) do
      address when is_binary(address) and address != "" -> reply_to(email, address)
      _other -> email
    end
  end
end
