import { transporterApi, type TransporterProductOption } from "@/lib/api/transporter";
import { requireServerToken } from "@/lib/auth/server";
import ProductPicker from "./ProductPicker";

async function loadProducts(token: string): Promise<TransporterProductOption[]> {
  try {
    return (await transporterApi.products(token)).data;
  } catch {
    return [];
  }
}

/**
 * Server-rendered: the token comes from the cookie during SSR, so the commodity
 * list is fetched before the response is sent and the `Loader` branch disappears
 * entirely — there is nothing left to wait for once the HTML arrives.
 *
 * Only the picker below is a Client Component, because toggling a card has to
 * repaint its ring without a round trip. Saving is a Server Action, so the
 * selection no longer travels through a hand-rolled `fetch`.
 */
export default async function TransporterProductsPage() {
  const token = await requireServerToken("/transporter/products");
  const list = await loadProducts(token);

  return <ProductPicker items={list} />;
}
