defmodule Berrypod.ContactNotifier do
  @moduledoc """
  Sends contact form submissions to the shop owner.
  """

  import Swoosh.Email

  alias Berrypod.{Mailer, Settings}

  require Logger

  @doc """
  Delivers a contact form message to the shop owner's email.

  Expects a map with "name", "email", and "message" keys (string keys,
  as received from form params). "subject" is optional.
  """
  def deliver_contact_message(%{"name" => name, "email" => email, "message" => message} = params)
      when is_binary(name) and name != "" and is_binary(email) and email != "" and
             is_binary(message) and message != "" do
    subject =
      if params["subject"] in [nil, ""], do: "Contact form message", else: params["subject"]

    shop_name = Settings.get_setting("shop_name", "Berrypod")
    from_address = Settings.get_setting("email_from_address", "contact@example.com")
    to_address = Settings.get_setting("contact_email") || from_address

    body = """
    ==============================

    New message from your #{shop_name} contact form

    Name: #{name}
    Email: #{email}
    Subject: #{subject}

    #{message}

    ==============================
    """

    email_msg =
      new()
      |> to(to_address)
      |> from({shop_name, from_address})
      |> reply_to(email)
      |> subject("[#{shop_name}] #{subject}")
      |> text_body(body)

    case Mailer.deliver(email_msg) do
      {:ok, _metadata} = result ->
        result

      {:error, reason} = error ->
        Logger.warning("Failed to send contact form email: #{inspect(reason)}")
        error
    end
  end

  def deliver_contact_message(_), do: {:error, :invalid_params}
end
