defmodule BerrypodWeb.ContactControllerTest do
  use BerrypodWeb.ConnCase, async: false

  import Berrypod.AccountsFixtures
  import Swoosh.TestAssertions

  setup do
    user_fixture()
    {:ok, _} = Berrypod.Settings.set_site_live(true)
    # Clear confirmation email from user_fixture
    Swoosh.TestAssertions.assert_email_sent()
    :ok
  end

  describe "POST /contact/send" do
    test "sends email and redirects with success flash", %{conn: conn} do
      conn =
        post(conn, ~p"/contact/send", %{
          "name" => "Jo Bloggs",
          "email" => "jo@example.com",
          "subject" => "Question",
          "message" => "Do you ship internationally?"
        })

      assert redirected_to(conn) == "/contact"
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Message sent"

      assert_email_sent(fn email ->
        assert email.subject =~ "Question"
        assert email.text_body =~ "Do you ship internationally?"
      end)
    end

    test "redirects with error flash when required fields missing", %{conn: conn} do
      conn = post(conn, ~p"/contact/send", %{"name" => "", "email" => "", "message" => ""})

      assert redirected_to(conn) == "/contact"
      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "required fields"
    end

    test "redirects with error flash when params empty", %{conn: conn} do
      conn = post(conn, ~p"/contact/send", %{})

      assert redirected_to(conn) == "/contact"
      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "required fields"
    end
  end
end
