defmodule Berrypod.ContactNotifierTest do
  use Berrypod.DataCase, async: true

  import Swoosh.TestAssertions

  alias Berrypod.ContactNotifier
  alias Berrypod.Settings

  describe "deliver_contact_message/1" do
    test "sends email with valid params" do
      assert {:ok, _} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "Jo Bloggs",
                 "email" => "jo@example.com",
                 "subject" => "Question about prints",
                 "message" => "Do you ship to Mars?"
               })

      assert_email_sent(fn email ->
        assert email.subject =~ "Question about prints"
        assert email.text_body =~ "Jo Bloggs"
        assert email.text_body =~ "jo@example.com"
        assert email.text_body =~ "Do you ship to Mars?"
        assert {"", "jo@example.com"} = email.reply_to
      end)
    end

    test "sends to contact_email when set" do
      Settings.put_setting("contact_email", "shop@example.com")

      assert {:ok, _} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "Test",
                 "email" => "test@example.com",
                 "message" => "Hello"
               })

      assert_email_sent(fn email ->
        assert [{"", "shop@example.com"}] = email.to
      end)
    end

    test "uses default subject when not provided" do
      assert {:ok, _} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "Test",
                 "email" => "test@example.com",
                 "message" => "Hello"
               })

      assert_email_sent(fn email ->
        assert email.subject =~ "Contact form message"
      end)
    end

    test "returns error for missing name" do
      assert {:error, :invalid_params} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "",
                 "email" => "test@example.com",
                 "message" => "Hello"
               })
    end

    test "returns error for missing email" do
      assert {:error, :invalid_params} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "Test",
                 "email" => "",
                 "message" => "Hello"
               })
    end

    test "returns error for missing message" do
      assert {:error, :invalid_params} =
               ContactNotifier.deliver_contact_message(%{
                 "name" => "Test",
                 "email" => "test@example.com",
                 "message" => ""
               })
    end

    test "returns error for missing keys" do
      assert {:error, :invalid_params} = ContactNotifier.deliver_contact_message(%{})
    end
  end
end
