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

  import Berrypod.AccountsFixtures
  import Berrypod.OrdersFixtures

  alias Berrypod.EmailSession

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

  describe "POST /contact/lookup" do
    test "sends lookup email and redirects when orders exist", %{conn: conn} do
      order_fixture(%{customer_email: "buyer@test.com", payment_status: "paid"})

      conn = post(conn, ~p"/contact/lookup", %{"email" => "buyer@test.com"})

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

    test "shows error when no orders found", %{conn: conn} do
      conn = post(conn, ~p"/contact/lookup", %{"email" => "nobody@test.com"})

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

    test "shows error when email is missing", %{conn: conn} do
      conn = post(conn, ~p"/contact/lookup", %{})

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

  describe "GET /orders/verify/:token" do
    test "sets email session cookie and redirects to orders page", %{conn: conn} do
      order_fixture(%{customer_email: "buyer@test.com", payment_status: "paid"})
      token = BerrypodWeb.OrderLookupController.generate_token("buyer@test.com")

      conn = get(conn, ~p"/orders/verify/#{token}")

      assert redirected_to(conn) == "/orders"

      # 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 "returns error for invalid token", %{conn: conn} do
      conn = get(conn, ~p"/orders/verify/invalid-token")

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