defmodule ToweropsWeb.Plugs.CaptureTimezone do
  @moduledoc """
  Captures the cf-timezone header from Cloudflare and stores it in session.

  Cloudflare provides timezone detection via the cf-timezone header using
  IANA timezone database format (e.g., "America/Chicago", "Europe/London").

  Falls back to "UTC" if the header is not present (development, non-Cloudflare).
  """
  import Plug.Conn

  @doc false
  def init(opts), do: opts

  @doc false
  def call(conn, _opts) do
    case get_req_header(conn, "cf-timezone") do
      [tz] when is_binary(tz) and byte_size(tz) > 0 ->
        # Cloudflare header present - use it
        put_session(conn, :detected_timezone, tz)

      _ ->
        # No Cloudflare header - only set if not already in session (allows test mocking)
        # Check both atom and string keys since session keys may be converted by Phoenix
        existing_tz = get_session(conn, :detected_timezone) || get_session(conn, "detected_timezone")

        if existing_tz do
          # Already set (possibly by test setup) - don't overwrite
          # But ensure it's stored with atom key for consistency
          put_session(conn, :detected_timezone, existing_tz)
        else
          # Not set - default to UTC
          put_session(conn, :detected_timezone, "UTC")
        end
    end
  end
end
