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

  import Berrypod.AccountsFixtures
  import Berrypod.OrdersFixtures

  alias Berrypod.{EmailSession, Orders}

  setup do
    user_fixture()
    {:ok, _} = Berrypod.Settings.set_site_live(true)
    :ok
  end

  describe "GET /checkout/complete" do
    test "sets email session cookie and redirects to success page when order found", %{conn: conn} do
      order = order_fixture(%{customer_email: "buyer@test.com"})
      {:ok, order} = Orders.set_stripe_session(order, "cs_test_123")

      conn = get(conn, ~p"/checkout/complete", %{"session_id" => order.stripe_session_id})

      assert redirected_to(conn) == "/checkout/success?session_id=cs_test_123"

      # Verify the email session cookie was set
      cookie = conn.resp_cookies[EmailSession.cookie_name()]
      assert cookie != nil
      assert cookie.max_age == 30 * 24 * 60 * 60
    end

    test "redirects without setting cookie when order not found", %{conn: conn} do
      conn = get(conn, ~p"/checkout/complete", %{"session_id" => "nonexistent"})

      assert redirected_to(conn) == "/checkout/success?session_id=nonexistent"

      # No cookie should be set
      assert conn.resp_cookies[EmailSession.cookie_name()] == nil
    end

    test "redirects to home when no session_id provided", %{conn: conn} do
      conn = get(conn, ~p"/checkout/complete")

      assert redirected_to(conn) == "/"
    end
  end
end
