defmodule BerrypodWeb.Plugs.EmailSession do
  @moduledoc """
  Plug that loads the verified email from the email session cookie into assigns.

  This makes `@email_session` available in controllers and LiveViews,
  containing the verified email address if the customer has one.
  """

  import Plug.Conn

  alias Berrypod.EmailSession

  def init(opts), do: opts

  def call(conn, _opts) do
    case EmailSession.get_email(conn) do
      {:ok, email} ->
        conn
        |> assign(:email_session, email)
        |> put_session("email_session", email)

      :error ->
        assign(conn, :email_session, nil)
    end
  end
end
