defmodule SimpleshopThemeWeb.CartController do
  @moduledoc """
  API controller for cart session persistence.

  LiveView cannot write to session directly, so cart updates are persisted
  via this API endpoint called from a JS hook after each cart modification.
  """

  use SimpleshopThemeWeb, :controller

  alias SimpleshopTheme.Cart

  @doc """
  Updates the cart in session.

  Expects JSON body with `items` as a list of [variant_id, quantity] arrays.
  """
  def update(conn, %{"items" => items}) when is_list(items) do
    cart_items = Cart.deserialize(items)

    conn
    |> Cart.put_in_session(cart_items)
    |> json(%{ok: true})
  end

  def update(conn, _params) do
    conn
    |> put_status(:bad_request)
    |> json(%{error: "Invalid cart data"})
  end
end
