defmodule Berrypod.EmailSession do
  @moduledoc """
  Manages persistent email sessions for verified customers.

  Used for order lookup, review submission, and review editing without
  requiring re-verification each time. The session is stored as a signed
  cookie that lasts 30 days.

  Unlike the short-lived order lookup tokens (1 hour), this provides a
  "remember me" style experience for returning customers.
  """

  import Plug.Conn

  @cookie_name "email_session"
  @max_age 30 * 24 * 60 * 60
  @salt "email_session_v1"

  @doc """
  Sets the email session cookie for a verified email address.

  Call this after successful email verification (order lookup, review
  submission, checkout completion) to enable the customer to access
  their orders and reviews without re-verifying.
  """
  def put_session(conn, email) when is_binary(email) do
    email = String.downcase(String.trim(email))
    token = Phoenix.Token.sign(BerrypodWeb.Endpoint, @salt, email)

    put_resp_cookie(conn, @cookie_name, token,
      max_age: @max_age,
      http_only: true,
      secure: Application.get_env(:berrypod, :env) == :prod,
      same_site: "Lax"
    )
  end

  @doc """
  Retrieves the verified email address from the session cookie.

  Returns `{:ok, email}` if the cookie is valid and not expired,
  or `:error` otherwise.
  """
  def get_email(conn) do
    with token when is_binary(token) <- conn.cookies[@cookie_name],
         {:ok, email} <-
           Phoenix.Token.verify(BerrypodWeb.Endpoint, @salt, token, max_age: @max_age) do
      {:ok, email}
    else
      _ -> :error
    end
  end

  @doc """
  Clears the email session cookie.

  Use when the customer explicitly logs out or requests to be forgotten.
  """
  def clear_session(conn) do
    delete_resp_cookie(conn, @cookie_name)
  end

  @doc """
  Returns the cookie name for testing purposes.
  """
  def cookie_name, do: @cookie_name
end
