defmodule Berrypod.EmailSessionTest do
  use BerrypodWeb.ConnCase, async: true

  alias Berrypod.EmailSession

  describe "put_session/2" do
    test "sets a signed cookie with the email", %{conn: conn} do
      conn = EmailSession.put_session(conn, "test@example.com")

      assert cookie = conn.resp_cookies[EmailSession.cookie_name()]
      assert cookie.max_age == 30 * 24 * 60 * 60
      assert cookie.http_only == true
      assert cookie.same_site == "Lax"
    end

    test "normalises email to lowercase", %{conn: conn} do
      conn = EmailSession.put_session(conn, "TEST@EXAMPLE.COM")
      cookie = conn.resp_cookies[EmailSession.cookie_name()]

      # The cookie value is a signed token, so we verify by getting it back
      conn = %{conn | cookies: %{EmailSession.cookie_name() => cookie.value}}
      assert {:ok, "test@example.com"} = EmailSession.get_email(conn)
    end

    test "trims whitespace from email", %{conn: conn} do
      conn = EmailSession.put_session(conn, "  test@example.com  ")
      cookie = conn.resp_cookies[EmailSession.cookie_name()]

      conn = %{conn | cookies: %{EmailSession.cookie_name() => cookie.value}}
      assert {:ok, "test@example.com"} = EmailSession.get_email(conn)
    end
  end

  describe "get_email/1" do
    test "returns the email from a valid cookie", %{conn: conn} do
      conn = EmailSession.put_session(conn, "buyer@shop.com")
      cookie = conn.resp_cookies[EmailSession.cookie_name()]

      conn = %{conn | cookies: %{EmailSession.cookie_name() => cookie.value}}
      assert {:ok, "buyer@shop.com"} = EmailSession.get_email(conn)
    end

    test "returns :error when no cookie present", %{conn: conn} do
      conn = %{conn | cookies: %{}}
      assert :error = EmailSession.get_email(conn)
    end

    test "returns :error for invalid token", %{conn: conn} do
      conn = %{conn | cookies: %{EmailSession.cookie_name() => "invalid-token"}}
      assert :error = EmailSession.get_email(conn)
    end
  end

  describe "clear_session/1" do
    test "deletes the cookie", %{conn: conn} do
      conn =
        conn
        |> EmailSession.put_session("test@example.com")
        |> EmailSession.clear_session()

      assert conn.resp_cookies[EmailSession.cookie_name()].max_age == 0
    end
  end
end
