defmodule WhoNeedHelp.Support.Notifier do
  import Swoosh.Email

  alias WhoNeedHelp.Mailer
  alias WhoNeedHelp.Support.SupportRequest

  def deliver_received(%SupportRequest{} = request, status_url) do
    deliver(
      request.contact_email,
      "Who Need Help support request #{request.reference}",
      """
      We received your support request #{request.reference}.

      Subject: #{request.subject}
      Status: #{request.status}

      View the current status:
      #{status_url}

      If there is immediate danger, contact the emergency service for your location.
      """
    )
  end

  def deliver_decision(%SupportRequest{} = request, status_url) do
    deliver(
      request.contact_email,
      "Who Need Help support update #{request.reference}",
      """
      Your support request #{request.reference} was updated.

      Status: #{request.status}
      Response:
      #{request.resolution_note || "No additional response was provided."}

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

  def deliver_operator_alert(%SupportRequest{} = request) do
    case Application.get_env(:who_need_help, :support_inbox_address) do
      address when is_binary(address) and address != "" ->
        deliver(
          address,
          "New support request #{request.reference}",
          """
          A new #{request.kind} support request is waiting for review.

          Reference: #{request.reference}
          Operator queue: #{WhoNeedHelpWeb.Endpoint.url()}/support/operations

          Sign in with an authorised moderator or administrator account to review it.
          """
        )

      _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
