import { json } from "@remix-run/node";
import { getTurn14AccessTokenFromMetafield } from "../../../utils/turn14Token.server";

export const loader = async ({ request }) => {
  const url = new URL(request.url);
  const brand = url.searchParams.get("brand");
  const page  = url.searchParams.get("page") || "1";

  // Get the Turn14 token (server‐only)
  const token = await getTurn14AccessTokenFromMetafield(request);

  // Fetch Turn14 items
  const res = await fetch(
    `https://turn14.data4autos.com/v1/items/brand/${brand}?page=${page}`,
    {
      headers: { Authorization: `Bearer ${token}` },
    }
  );
  if (!res.ok) {
    return json({ error: "Failed to fetch Turn14 items" }, { status: res.status });
  }
  const data = await res.json();
  return json(data);
};
